Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose populate multiple nested documents

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.

like image 758
Alistair Avatar asked Mar 02 '16 08:03

Alistair


2 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'
        }]
    })
like image 163
Fucazu Avatar answered Sep 17 '22 18:09

Fucazu


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);
  }
like image 26
Naveen Kumar Avatar answered Sep 17 '22 18:09

Naveen Kumar