2016-11-23 1 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

関連する問題