I would like to deep populate a perhaps overcomplicated model
var ParentSchema = new Schema({
childs: [{type:Schema.ObjectId, ref: 'Child'}],
});
var ChildSchema = new Schema({
subject: [{
price: {type: Number},
data: {type: Schema.ObjectId, ref: 'Subject'}
}]
})
However, it doesn't seem to work when i use the regular population. I installed deep-populate now and use the following:
Parent.deepPopulate('childs.subjects');
I was wondering if there is perhaps an easier way to accomplish a populated array of subjects.
The mongoose-deep-populate plugin will work for this, but you need to use the right path to the deepest field you want populated. In this case, the query should look like this:
Parent.findOne().deepPopulate('childs.subject.data').exec(function(err, parents) {...});
However, it's important to realize this uses multiple queries (at least one per population level) to perform the population. First the Parent
query, then the Child
query, and then the Subject
query. As such, it's best to embed related data when possible, but that's not practical if you need to query the child and subject data independently. So if you need your related docs in separate collections, population is the way to go.
See the section of the docs on data modeling for more info and guidance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With