我想更新我的mongo文档中的份量,卡路里和营养素。我怎样才能更新细节?
{
"_id": ObjectId("id"),
"user_id": ObjectId("id"),
"date": 20170210,
"snacks": [
{
"nutrients": {
"protein": "0",
"carbs": "0",
"fat": "0"
},
"servings": 1,
"calories": 0.35,
"name": "Coca-Cola zero"
}
],
"dinner": [ ],
"lunch": [ ],
"breakfast": [ ]
}
我尝试使用$ set但它根本没用。这就是我一直在尝试的:
user_food.update({user_id : req.session.user_id, date: 20170210, snacks:{name:"Coca-Cola zero"}}, {'$set':{'servings': 2}}, function(err, other){
if(err){
console.log("something went wrong: " + err);
return res.status(500).send(err);
}
else{
console.log("this is other: " + other);
return res.status(200).send(other);
}
});
解决
有效的查询:
user_food.update({user_id : req.session.user_id, date: 20170210, 'snacks.name': food},{$set: {'snacks.$.servings': serving}},function(err, other){
if(err){
console.log("something went wrong: " + err);
return res.status(500).send(err);
}
else{
console.log("this is other: " + other);
return res.status(200).send(other);
}
});
答案 0 :(得分:0)
您必须指定记录必须包含属性snacks.name = 'Coca-Cola zero'
而不是snacks = {name: 'Coca-Cola zero'}
。
所以你的查询应该是这样的:
user_food.update({
user_id : req.session.user_id,
date: 20170210,
'snacks.name': 'Coca-Cola zero'
},{
$set: {'snacks.$servings': 2}
},
function(err, other){
if(err){
console.log("something went wrong: " + err);
return res.status(500).send(err);
}
else{
console.log("this is other: " + other);
return res.status(200).send(other);
}
});