Home > Mobile >  mongoose update on array of objects
mongoose update on array of objects

Time:11-24

im trying to make an update on my bd, but the problem is that i dont have an id per object, the only thing i can identify by its the "description" property. I want to update that property value but first i have to find it and update it as well, this is the json

{
  "_id": {
    "$oid": "637c1064a2f047f5ab75ac42"
  },
  "title": "this is a list",
  "todo": [
    {
      "completed": false,
      "description": "a normal task"
    },
    {
      "completed": false,
      "description": "this is another task"
    },
    {
      "completed": false,
      "description": "another task"
    }
  ],
  "username": "lucas",
  "__v": 3
}

This is what im trying to do, im trying to update the property description with a new description, but first i have to find the same element that matches with whats in the body.

  List.findOneAndUpdate(
        {todo: {description: req.body.description}},// trying to find it here
        {$set:{todo : {description: req.body.newDescription}}}, //trying to change it here
        function(err, response) {
            console.log(err,response)
          }
    )

CodePudding user response:

You have a couple mistakes:

First one is you are using {todo: {description: req.body.description}} to find the object. In this way, mongo tries to compare using the whole object, that means only will return a match if todo is equal to description: value. But todo is an array and it contains objects.

Take a look to the dot notation docs

The second part is to use positional operator $. With $ you can tell mongo "get the element you have found in the prevous stage and update with the new value".

So you can try this query:

List.findOneAndUpdate({
  "todo.description": req.body.description
},
{
  "$set": {
    "todo.$.description": req.body.newDescription
  }
})

Example here

  • Related