I have a mongoose model that looks like this:
var ModuleSchema = new Schema({
systems: [{
system: {
type: Schema.ObjectId,
ref: 'System'
},
quantity: {
type: Number
}
}]
});
mongoose.model('Module', ModuleSchema);
Basically the ModuleSchema.systems.$.system property will not get populated.
The property belongs to an object in the array of objects. I have tried everything to get it to populate but it just won't happen.
I tried the following syntax for populating but not sure what might be wrong because I still don't get back the populated System property.
Module.findOne({project: pId}).sort('-created')
.populate('systems.system')
It wont work as system is not a property of systems. You need to populate it like
Module.findOne({project: pId}).sort('-created')
.populate('systems.0.system').exec(function (err, doc){})
Module.findOne({project: pId}).sort('-created')
.populate('systems.1.system').exec(function (err, doc){})
So you should have a for loop and iterate over it to populate all the documents. Else you should modify your model to make it work better.
var ModuleSchema = new Schema({
systems: [{
system: {
type: Schema.ObjectId,
ref: 'System'
},
quantity: {
type: Number
}
}]
});
Change your model to this and it will make easy for you.
var ModuleSchema = new Schema({
systems: {
system: [{
type: Schema.ObjectId,
ref: 'System'
}],
quantity: {
type: Number
}
}
});