我有一个具有组引用的用户。我想知道如何在组内填充游戏、用户和等级?所以我基本上想要的是在代码中的 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/