Mongoose填充多个嵌套文档

Ali*_*air 8 mongoose mongodb node.js

我搜索了高低,但无法弄清楚如何形成以下填充查询,首先是我的模型:

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' }],
});
Run Code Online (Sandbox Code Playgroud)

我有一个端点,它获得一个单一的课程,但我想填充classes字段和locationinstructors字段classes.现在,我可以填充教练场classeslocation,但我不能在同一时间填充他们两个.这就是我现在所拥有的:

    Course
        .findById(req.params.courseId)
        .populate({
            path: 'classes',
            populate: {
                path: 'instructors',
                model: 'User'
            }
        })
Run Code Online (Sandbox Code Playgroud)

我怎样才能填充该location字段classes

谢谢.

小智 41

兴趣替代方案是将数组传递给嵌套的填充.

Course
    .findById(req.params.courseId)
    .populate({
        path: 'classes',
        model: 'Classroom',
        populate: [{
            path: 'instructors',
            model: 'User'
        },
        {
            path: 'location',
            model: 'Location'
        }]
    })
Run Code Online (Sandbox Code Playgroud)

  • 如果在该填充数组中,我们需要再添加一个填充呢?那可能吗? (2认同)

zan*_*ngw 7

请在猫鼬v4下尝试这个,这是一个很好的链接 Population

   Course
        .findById(req.params.courseId)
        .populate({
            path: 'classes',
            model: 'Classroom',
            populate: {
                path: 'instructors',
                model: 'User'           
            }
        })
        .exec(function(err, cour) {
            if (err)
                console.log(err);
            else {
                Course.populate(cour, 
                    {
                        path: 'classes.location',
                        model: 'Location',
                    }, function(err, c1) {
                        if (err)
                            console.log(err);
                        else
                            console.log(util.inspect(c1, { showHidden: true, depth: null }));                       
                    })
            }
        })
Run Code Online (Sandbox Code Playgroud)


Nav*_*mar 5

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);
  }
Run Code Online (Sandbox Code Playgroud)