I've searched high and low but can't figure out how to form the following populate query, first here are my models:
const CourseSchema = new Schema({
classes: [{ type: Schema.Types.ObjectId, ref: 'Classroom' }]
});
const ClassSchema = new Schema({
location: { type: mongoose.Schema.Types.ObjectId, ref: 'Location' },
instructors: [{ type: mongoose.Schema.Types.ObjectId, ref: 'User' }],
});
I have an endpoint which gets a single course, but I want to populate the classes
field AND the location
and instructors
fields in classes
. Right now, I can either populate the instructors field in classes
or location
, but I can't populate both of them at the same time. This is what I have for now:
Course
.findById(req.params.courseId)
.populate({
path: 'classes',
populate: {
path: 'instructors',
model: 'User'
}
})
How can I also populate the location
field in classes
?
Thanks.
An interest alternative is pass an array to nested populate.
Course
.findById(req.params.courseId)
.populate({
path: 'classes',
model: 'Classroom',
populate: [{
path: 'instructors',
model: 'User'
},
{
path: 'location',
model: 'Location'
}]
})
Try the below code
getAllByQuery: function (query, callback) {
this
.find(query, {capId: 1})
.populate({path: 'capId',
model: 'cap',
select: {
'capDetail': 0,
'area': 0,
},
populate: [{
path: 'ad_Id',
model: 'Ad',
select: { 'Level': 1}
},
{
path: 'ctgs',
model: 'Ctgry',
select: { '_id': 0}
}]
})
.exec(callback);
}
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