-1

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

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for that but doesnt work, idk why, im sending this: { "title": "this is a list", "completed": false, "description": "this is another task", "newDescription" : "updated task", "username": "lucas" }
i try with findOneAndUpdate and updateOne
now works but with a function as third parameter, but why?
I think you have to try something like this
Do you use await? Otherwise you can get the data in the callback (the function)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.