1

I would like to update the servings, calories and nutrients in my mongo document. How would I be able to update the details?

{
"_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": [ ]
}

Ive tried using $set however it hasnt not worked at all. This is what ive been trying:

     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);
        }
    });

SOLVED

The query that worked:

        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);
        }
    });
William.Doyle
  • 79
  • 1
  • 10
  • I don't see `$set` in your example? – evolutionxbox Mar 10 '17 at 13:29
  • Try `user_food.update({user_id : req.session.user_id, date: 20170210, "snacks.name":"Coca-Cola zero"}, {'$set':{'snacks.$servings': 2}}, function(err, other){...})`. Make use of [positional](https://docs.mongodb.com/manual/reference/operator/update/positional/) opertor – s7vr Mar 10 '17 at 13:39
  • Possible duplicate of [Update field in exact element array in MongoDB](http://stackoverflow.com/questions/10432677/update-field-in-exact-element-array-in-mongodb) – s7vr Mar 10 '17 at 13:40

1 Answers1

0

You have to specify that the record must have the property snacks.name = 'Coca-Cola zero' and not snacks = {name: 'Coca-Cola zero'}.

So your query should look like:

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);
  }
});
TheGr8_Nik
  • 3,080
  • 4
  • 18
  • 33
  • whenever i try that I get the following error message "cannot use the part (snacks of snacks.$servings) to traverse the element ({snacks: [ { nutrients: { protein: "0", carbs: "0", fat: "0" }, servings: 1, calories: 0.35, name: "Coca-Cola zero" } ]})" – William.Doyle Mar 10 '17 at 16:42