【问题标题】:populate multiple sub documents填充多个子文档
【发布时间】:2017-04-06 21:15:57
【问题描述】:

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

用户模式

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);
    }
  })

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    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

    【讨论】:

      猜你喜欢
      • 2016-01-21
      • 2014-08-16
      • 2017-01-27
      • 1970-01-01
      • 2017-05-07
      • 2017-03-21
      • 2017-06-06
      • 2018-08-16
      • 2017-03-14
      相关资源
      最近更新 更多