Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose, Deep Population on array model

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.

like image 876
Maxim Avatar asked Jun 02 '15 11:06

Maxim


1 Answers

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.

like image 162
JohnnyHK Avatar answered Oct 12 '22 08:10

JohnnyHK