Krisalay Krisalay - 3 months ago 20
Node.js Question

error updating data in mongodb using nodejs

I have the data in mongodb as:

{
"_id":ObjectId("5415dsc5fdvfv15vff65"),
"username":"myusername",
"friends": [
{
"name":"friend1",
"isFriend":false
},
{
"name":"friend2",
"isFriend":false
}
]
}


Now I am trying to update my 'isFriend' status to 'true'.

my nodejs code for updation is:

User.update({username:'myUsername',friends.name:'friend1'},{$set:{friends:{name:'friend1',isFriend:true}}}, function(err,val){
console.log(val.nModified);
});


But this code shows an error Unexpected token . in friends.name

How do we do this??

Answer

Try this..

User.update({username:'myUsername','friends.name':'friend1'},{$set:{ "friends.$.name" : "updated name","friends.$.isFriend":true }}, function(err,val){
 console.log(val.nModified);
});