Ravi Singh
Ravi Singh

Reputation: 1119

How to update the childs value of an object present in the mongod using mongoose with node.js?

i want to update particular child's value which is actually present inside the object and wants all my rest value be the same. i want to use mongoose npm package.

for example:

basic:{
 name: "ABC",
 mobile: 1234567890,
 age: 20
},
other:{
 pincode: 123456,
 email: "[email protected]"
}

My Code

 Model.findOneAndUpdate(
  { "basic.mobile": 1234567890 },
     {
           basic:{ name: "CDE"}
     },
     (err, doc) => {
       if (err) return res.send({ error: err });
       res.send(`updated`);
     }
 );

it works but it override the previous basic data and create a new one which i provided. it should update but also rest value should be there. how can i do this?

Upvotes: 0

Views: 441

Answers (1)

Lucia
Lucia

Reputation: 855

Your question contains the answer. For Filter you are referring a single field using dot operator properly that is

"basic.mobile": 1234567890

You should do similar thing for update as well, that is the second argument of your function call, the way you have defined is wrong becuase it is a new object - that should be used when you want replace whole basic object in DB. If you want to just update the name field then you should use dot operator like below.

"basic.name":"CDE"

So the whole function would look like below.

Model.findOneAndUpdate(
     { "basic.mobile": 1234567890 },
     { "basic.name": "CDE"},
     (err, doc) => {
       if (err) return res.send({ error: err });
       res.send(`updated`);
     }
 );

Upvotes: 2

Related Questions