填充多个子文档

时间:2016-11-23 01:42:35

标签: node.js mongodb mongoose

我有一个拥有群组参考的用户。我想知道我如何填充群体中的游戏,用户和排名?所以我基本上想要的是在代码中的user.group中填充这3个值

用户模式

var userSchema = new Schema({
  fb: {
    type: SchemaTypes.Long,
    required: true,
    unique: true
  },
  name: String,
  birthday: Date,
  country: String,
  image: String,
  group: { type: Schema.Types.ObjectId, ref: 'Group'}

});

群组模型

var groupSchema = new Schema({
  users: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User'
  }],
  game: { type: Schema.Types.ObjectId, ref: 'Game' },
  ranks: [{
    type: Schema.Types.ObjectId, ref: 'Ladder'
  }]

});

  User.findByIdAndUpdate(params.id, {$set:{group:object._id}}, {new: true}, function(err, user){
    if(err){
      res.send(err);
    } else {
      res.send(user);
    }
  })

1 个答案:

答案 0 :(得分:5)

Mongoose 4支持填充多个级别。 Populate Docs如果您的架构是:

var userSchema = new Schema({
  name: String,
  friends: [{ type: ObjectId, ref: 'User' }]
});

然后你可以使用:

User.
  findOne({ name: 'Val' }).
  populate({
    path: 'friends',
    // Get friends of friends - populate the 'friends' array for every friend
    populate: { path: 'friends' }
  });

所以在你的情况下它应该是这样的:

User.findById(params.id)
.populate({
  path: 'group',
  populate: {
    path: 'users game ranks'
  }
})
.exec( function(err, user){
    if(err){
      res.send(err);
    } else {
      res.send(user);
    }
  })

类似问题here

相关问题