Mongoose填充多个嵌套文档

问题描述 投票:7回答:3

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

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

我有一个获得单一课程的终点,但我想在classes中填充location字段和instructorsclasses字段。现在,我可以填充classeslocation中的教师字段,但我不能同时填充它们。这就是我现在所拥有的:

    Course
        .findById(req.params.courseId)
        .populate({
            path: 'classes',
            populate: {
                path: 'instructors',
                model: 'User'
            }
        })

我怎样才能在location中填充classes字段?

谢谢。

node.js mongodb mongoose
3个回答
5
投票

请在mongoose 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 }));                       
                    })
            }
        })

39
投票

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

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

2
投票
Try the below code    


getAllByQuery: function (query, callback) {
    this
      .find(query, {campaignId: 1})
      .populate({path: 'campaignId',
        model: 'campaign',
        select: {
          'campaignDetail': 0,
          'area': 0,
        },
        populate: [{
          path: 'ad_Id',
          model: 'Ad',
          select: { 'Level': 1}
        },
        {
          path: 'categories',
          model: 'Category',
          select: { '_id': 0}
        }]
      })
      .exec(callback);
  }
© www.soinside.com 2019 - 2024. All rights reserved.