2
我試圖更新JSON場「champ_x」從1到3並在同一時間在一個動態函數雙方球員1:更新裏面的對象與貓鼬信息,內部對象數組動態
{
"_id": {
"$oid": "58a3521edf127d0a0c417cda"
},
"room": "room_0.0940045412694186",
"player_1": "eee",
"player_2": "fff",
"player_1_details": {
"history_moves": [],
"champions": [
{
"champ_1": "na"
},
{
"champ_2": "na"
},
{
"champ_3": "na"
}
]
},
"player_2_details": {
"history_moves": [],
"champions": [
{
"champ_1": "na"
},
{
"champ_2": "na"
},
{
"champ_3": "na"
}
]
},
"game_state": "789",
"__v": 0
}
我有這個模型:
match_schema.statics.update_champ = function(room, turn, champ_num, champ_select, callback){
if(champ_num == "champ_1"){
match_mongoose.update({ room: room }, { $set: { 'player_1_details.champions.0.champ_1': champ_select}})
.exec(function(error){
if(error){ return callback(error); }else{ return callback(null); }
});
}
};
這個優良樣板工程
我的問題是,我試圖讓它動態的,我可以通過函數只發送參數的當前轉(1或2)和t他選擇了位置(冠軍1,2或3)。
我已經試過這樣:
//Update Champion
match_schema.statics.update_champ = function(room, turn, champ_num, champ_select, callback){
match_mongoose.update({ room: room }, { $set: { 'player_'+turn+'_details.champions.0.'+champ_num: champ_select}})
.exec(function(error){
if(error){ return callback(error); }else{ return callback(null); }
});
};
var match_mongoose = mongoose.model('matches', match_schema, 'matches');
module.exports = match_mongoose;
但我得到的是說「意外令牌+」好像串聯值不起作用的錯誤。有沒有辦法做到這一點?
謝謝!
[Nodejs Mongo insert into subdocument - dynamic fieldname](http://stackoverflow.com/questions/12184626/nodejs-mongo-insert-into-subdocument-dynamic-fieldname) – dNitro