猫鼬-填充子模式子数组 [英] mongoose - populate sub-schema sub-array
问题描述
我正在尝试填充子模式字段.
I'm trying to populate a sub-schema field.
一个项目包含多个 ProjectFilters . 每个 ProjectFilter 都引用一个 FilterValue . FilterValue (一个 FilterValue )包含在一个(并且只有一个) Filter 中.
A Project contains multiple ProjectFilters. Each ProjectFilter references one FilterValue. A FilterValue is contained into one (and only one) Filter.
ProjectSchema
const ProjectSchema = new Schema({
title: String,
filters: [ProjectFilter.schema],
}, {
timestamps: true,
toJSON: {
virtuals: true,
},
});
ProjectFilterSchema
const ProjectFilterSchema = new Schema({
filterValue: {
type: mongoose.Schema.Types.ObjectId,
ref: 'FilterValue',
},
isMain: {
type: Boolean,
default: false,
},
}, {
toJSON: {
virtuals: true,
},
});
FilterSchema
const FilterSchema = new Schema({
label: String,
values: [FilterValue.schema],
}, {
timestamps: true,
toJSON: {
virtuals: true
},
});
FilterValueSchema
const FilterValueSchema = new Schema({
label: String,
color: String,
}, {
toJSON: {
virtuals: true,
},
});
此查询无效. filterValue是null
:
This query doesn't work. filterValue is null
:
let query = Project.findById(req.params.projectId, { _id: 0, filters: 1 });
query.populate('filters.filterValue');
我尝试使用虚拟填充:
ProjectFilterSchema.virtual('usedValue', {
ref: 'Filter',
localField: 'filterValue',
foreignField: 'values._id',
justOne : true,
});
但这会返回整个 Filter 文档,而不仅仅是所需的 FilterValue .
But this returns the whole Filter document, not only the FilterValue needed.
推荐答案
要填充子文档,首先需要明确定义ID引用到的文档集合. 这样,猫鼬就会知道要查询哪个集合.
In order to populate a subdocuments, first you will need to explicitly define the document collection to which the ID references to. That way, mongoose will know which collection to query.
(在Mongoose 4中,您可以跨多个级别填充文档)
(In Mongoose 4 you can populate documents across multiple levels)
//ES6 syntax
import mongoose from 'mongoose';
const Schema = mongoose.Schema;
const ObjectId = Schema.Types.ObjectId;
const FilterSchema = new Schema({
label: String,
filtervalues: [FilterValueSchema],
}, { collection: 'filter' })
const FilterValueSchema = new Schema({
label: String,
color: String,
}, { collection: 'filtervalue' })
const ProjectFilterSchema = new Schema({
filterValue: {
type: ObjectId,
ref: 'filtervalue',
}, { collection: 'projectfilter' })
mongoose.model('filters', ProjectFilterSchema);
mongoose.model('projectfilter', ProjectFilterSchema);
mongoose.model('filtervalue', FilterValueSchema);
Project.findById(req.params.projectId, { _id: 0 })
.populate('filters.filter.filterValue').
这篇关于猫鼬-填充子模式子数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!