2016-11-23 65 views
0

我有一個用戶使用組參考。我想知道我是如何填充遊戲,用戶和組內的隊伍?所以我基本上要在代碼填充多個子文檔

用戶模式

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); 
    } 
    }) 
來填充 user.group這3個值

回答

2

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