Mongoose:填充数组中对象的问题

时间:2016-01-18 05:44:09

标签: javascript mongodb express mongoose mean-stack

我有以下三种模式:

var User = {
first_name: String,
last_name: String,
}

var Student = {
role = String,
user = {type: mongoose.Schema.Types.ObjectId, ref: 'User'}
groups = [{type: mongoose.Schema.Types.ObjectId, ref: 'Group'}],
}

var Group = {
name = String,
students = [{type: mongoose.Schema.Types.ObjectId, ref: 'Student'}],
}

我的快速获取方法如下:

router.route('/')
  .get(function(req, res){
    Group.find().populate('students').exec(function(err, groups){
      res.json(groups);
    });

我的json对象返回已填充的学生对象数组,但我只从每个学生对象中接收user._id。我怎样才能让用户对象填充?任何信息都会很棒!感谢

1 个答案:

答案 0 :(得分:1)

您可以填充多个级别:

router.route('/')
  .get(function(req, res){
    Group
      .find()
      .populate({
        path: 'students',
        // Get the student's user ids
        populate: { path: 'user' }
      })
      .exec(function(err, groups){
        res.json(groups);
      });

您可以阅读更多相关信息here