node.js - 填充多个子文档

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

最佳答案

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

关于node.js - 填充多个子文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40754696/

相关文章:

c# - 使用 'ObjectId' 查询 MongoDB

node.js - Mongoose 深度填充多个二级对象不起作用

mongodb - 如何通过 Mongoose 更新 mongodb 中的对象?

javascript - 元数据版本不匹配 Angular 4 @ng-bootstrap

function - 没有对象包装器的 Node.JS 导出函数

javascript - 通过mongoose访问数组元素

mongodb - 避免 push/addToSet 空值到 mongodb 数组

node.js - Firebase:如何从 Android 和 iOS 验证 Google 登录 token ID

node.js - MongoDb - 要创建新的 ObjectId,请尝试 `Mongoose.Types.ObjectId` 而不是使用 `Mongoose.Schema.ObjectId`

javascript - 获取与父字段一起分配的所有文档