0

I want to add "3" to all "seenBy" array which is inside "Conversation" array.

{
  _id : 1,
  name : "name",
  email : "email",
  conversation : [
      {
        message : "Hai",
        seenBy : [1,2]
      },
      {
        message : "Hai",
        seenBy : [1,2]
      },
      {
        message : "Hai",
        seenBy : [1,2]
      }
  ]
}

Expected result :

{
  name : "name",
  email : "email",
  conversation : [
      {
        message : "Hai",
        seenBy : [1,2,3]
      },
      {
        message : "Hai",
        seenBy : [1,2,3]
      },
      {
        message : "Hai",
        seenBy : [1,2,3]
      }
  ]
}

My code :

DB.Users.update({_id : 1}, {$addToSet : {"conversation.$[].seenBy" : 3}}, {}, function(err, result){
console.log(err);
console.log(result)
})

I get this error :

MongoError: cannot use the part (conversation of conversation.$[].seenBy) to traverse the element

Thanks in advance.

2 Answers 2

1

You're not specifying _id field in the data set u mentioned:

{
  name : "name",
  email : "email",
  conversation : [
  {
    message : "Hai",
    seenBy : [1,2]
  },
  {
    message : "Hai",
    seenBy : [1,2]
  },
  {
    message : "Hai",
    seenBy : [1,2]
  }
 ]
}

So, MongoDB add an ObjectID automatically, so you need to specify that. _id:1 will work if u have the specified _id in the DB. I'm getting proper output using your above query: enter image description here enter image description here

So, the issue is with your mongoose code and not with the Mongo query.

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

4 Comments

thomas get truw answer and run away:D
Sorry. Check my "Update" query. I am using "_id" to update the document.
Not funny :P @ŞükranEken
I am using mongoose and i don't know why its throwing error. @Rahul Raj
0

This is the way you can access nested array in document and push in it

Something like

db.Users.update(
{},
{ "$push": {"conversation.$[].seenBy": 3}}
)

Note. This will add 3 to all of your documents. You can add any filter based on your requirements

Comments

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.