0

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??

3 Answers 3

2

Try this..

User.update({username:'myUsername','friends.name':'friend1'},{$set:{ "friends.$.name" : "updated name","friends.$.isFriend":true }}, function(err,val){
 console.log(val.nModified);
});
Sign up to request clarification or add additional context in comments.

3 Comments

it gives the ouput {ok: 1, nModified: 0, n: 0 }, so the modification is not successful
it must be work if your username and friends.name values matches in query parameter. Check proper your both values.
yeah, i was making a mistake, Thanks. I have another query: how to add 'friend3' if 'friend3' does not exist in the array.
1

Nested criteria should be string

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

2 Comments

now the error is not showing, but the the data is also not getting updated. The value of val.nModified is 0.
@Krisalay The update part should be fixed. Another answer gives the right one. So I don't update mine.
0

It should be enough add double quotes "friends.name"

1 Comment

now the error is not showing, but the the data is also not getting updated. The value of val.nModified is 0.

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.