Pet*_*Pik 2 mongoose mongodb node.js
我有一个用户组参考.我想知道我如何填充游戏,用户和组内的排名?所以我基本上想要的是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'}
});
Run Code Online (Sandbox Code Playgroud)
小组模型
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'
}]
});
Run Code Online (Sandbox Code Playgroud)
码
User.findByIdAndUpdate(params.id, {$set:{group:object._id}}, {new: true}, function(err, user){
if(err){
res.send(err);
} else {
res.send(user);
}
})
Run Code Online (Sandbox Code Playgroud)
小智 5
Mongoose 4支持多个级别的填充.填充文档如果您的架构是:
var userSchema = new Schema({
name: String,
friends: [{ type: ObjectId, ref: 'User' }]
});
Run Code Online (Sandbox Code Playgroud)
然后你可以使用:
User.
findOne({ name: 'Val' }).
populate({
path: 'friends',
// Get friends of friends - populate the 'friends' array for every friend
populate: { path: 'friends' }
});
Run Code Online (Sandbox Code Playgroud)
所以在你的情况下它应该是这样的:
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);
}
})
Run Code Online (Sandbox Code Playgroud)
类似的问题在这里
| 归档时间: |
|
| 查看次数: |
989 次 |
| 最近记录: |