Answer a question

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.

Answers

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'
        }]
    })
Logo

MongoDB社区为您提供最前沿的新闻资讯和知识内容

更多推荐