Javascript Meteor(mongoDB)中对象数组中的更新字段
我有以下文件:Javascript Meteor(mongoDB)中对象数组中的更新字段,javascript,mongodb,meteor,Javascript,Mongodb,Meteor,我有以下文件: { "gameName":"Shooter", "details":[ { "submitted":1415215991387, "author":"XYZ", "subPlayer":{ "members":{ "squad1":[ { "username":"John"
{
"gameName":"Shooter",
"details":[
{
"submitted":1415215991387,
"author":"XYZ",
"subPlayer":{
"members":{
"squad1":[
{
"username":"John",
"deaths":0
}
]
},
"gameSlug":"0-shooter"
}
}
],
"userId":"foL9NpoZFq9AYmXyj",
"author":"Peter",
"submitted":1415215991608,
"lastModified":1415215991608,
"participants":[
"CXRR4sGf5AdvSjdgc",
"foL9NpoZFq9AYmXyj"
],
"slug":"1-shooterConv",
"_id":"p2QQ4TBwidjeZX6YS"
}
。。。以及以下流星法:
Meteor.methods({
updateDeaths: function(gameSlug, user, squad) {
Stats.update({details.subPlayer.gameSlug: gameSlug}, ...}); // ???
}
});
我的目标是更新字段死亡
。该方法具有参数user
,该参数是用户对象(username=user.username
)。此外,参数squad
是作为字符串的班名,例如squad1
我该怎么做
任何帮助都将不胜感激。您应该使用以下内容:
db.collection.update(
{'userId':'foL9NpoZFq9AYmXyj', 'details.subPlayer.gameSlug':'0-shooter'},
{'$set':
{'details': [{
'subPlayer': {
'members': {
'squad1':[{'username':'John','death':1}]
}
}
}]
}
}
)
UPD:
另外,可能更好的方法是使用find().snapshot().forEach()。但我不知道流星是如何支撑它的。例如:
Stats.find({'userId':'foL9NpoZFq9AYmXyj', 'details.subPlayer.gameSlug':'0-shooter' }).map(function (e) {
e.details.forEach(function (d) {
var squad = 'squad1';
d.subPlayer.members[squad].forEach(function (s) {
s.deaths = 10000;
});
});
Stats.update({'_id': e._id}, e);
});
谢谢你的帮助!然而,我认为这个功能在Meteor中是不可用的<代码>类型错误:对象[Object Object]没有方法“findAndModify”@user3475602我更新我的答案。您可以使用
db.collection.update()
而不是findAndModify()
谢谢!这很有效。但是,现在执行此更新后,将删除details.submitted
、details.author
和details.subPlayer.gameslaug
字段。您知道如何解决此问题吗?此外,如何使用字符串变量动态设置band
字段?例如var-squad='squad1'代码>@user3475602参见upd部分。