Thursday 4 May 2017

MongoDB update by search by id

Im trying to update an item in an array by searching for it by its id however it does not work. When i search with the items name it can be updated but many items could have the same name so this causes problems.

{
 "_id": ObjectId("590b68d0b195840897242dbd"),
 "user_id": ObjectId("58d2dd4c8207c28149dbc748"),
 "calories": 2065,
 "date": 20170404,
 "snacks": [ ],
 "dinner": [ ],
 "lunch": [ ],
 "breakfast": [
{
  "id": ObjectId("590b68e2b195840897242dbf"),
  "nutrients": {
    "protein": 10,
    "carbs": 76,
    "fat": 6
  },
  "servings": 30,
  "calories": 496,
  "image": "https://static.openfoodfacts.org/images/products/501/002/920/1642/front_en.9.200.jpg",
  "brand": "Weetabix",
  "name": "Weetos Chocolatey Hoops"
},
{
  "id": ObjectId("590b68ebb195840897242dc2"),
  "nutrients": {
    "protein": 4,
    "carbs": 5,
    "fat": 4
  },
  "servings": 200,
  "calories": 580,
  "image": "https://static.openfoodfacts.org/images/products/20017743/front_en.6.200.jpg",
  "brand": "Morning fresh",
  "name": "Whole milk"
}
 ],
 "__v": 0
}

The query that works is as follows:

        user_food.update({user_id : req.session.user_id, date: today, breakfast.name: foodName}, {$set: {.....}},function(err, other){
        if(err){
            console.log(err);
            return res.status(500).send(err);
        }
        else{
            console.log(other);
            return res.status(200).send(other);
        }
    });

Ive tried to just remove breakfast.name in turn for breakfast.id and then using the id value however it does not work. Any help is welcomed



via William.Doyle

No comments:

Post a Comment