Mongoose, Deep Population on an array model

I would like to deeply fill a possibly complex 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, this does not seem to work when I use a regular aggregate. Now I have set the fill depth and use the following:

Parent.deepPopulate('childs.subjects');

I was wondering if there is perhaps an easier way to execute a populated array of objects.

+4
source share
2 answers

The mongoose-deep-populate plugin will work for this, but you need to use the correct path to the deepest field that you want to fill. In this case, the request should look like this:

Parent.findOne().deepPopulate('childs.subject.data').exec(function(err, parents) {...});

, ( ). Parent, Child, Subject. , , , , . , , - .

. .

+9

deepPopulate, 2 :

  • subject.data​​p >

    3 ( , Child Subject), deepPopulate:

query = Parent.findOne().populate('childs');        
query.exec(function(err, parent) {
    if (err) {
      //manage error
    };
    // now we need to populate all childs with their subject
    Child.populate(parent.childs, {
        path: 'subject.data',
        model: 'Subject'
    },function(err){
      // parent object is completely populated
    });
});
+2

All Articles