问题
I'm trying to populate a sub-schema field.
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,
},
});
This query doesn't work. filterValue is null
:
let query = Project.findById(req.params.projectId, { _id: 0, filters: 1 });
query.populate('filters.filterValue');
I have tried to use a virtual populate:
ProjectFilterSchema.virtual('usedValue', {
ref: 'Filter',
localField: 'filterValue',
foreignField: 'values._id',
justOne : true,
});
But this returns the whole Filter document, not only the FilterValue needed.
回答1:
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.
(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').
来源:https://stackoverflow.com/questions/42762588/mongoose-populate-sub-schema-sub-array