2

I want to update a sub dictionary in an array.

my array like this

"comments" : [ 
        {
            "text" : "hi",
            "_id" : ObjectId("56c552dd0a0f08b502a56521"),
            "author" : {
                "id" : ObjectId("56c54c73f96c51370294f254"),
                "photo" : "",
                "name" : ""
            }
        }, 
        {
            "text" : "Good",
            "_id" : ObjectId("56c5911fc33b446c05a4dabc"),
            "author" : {
                "id" : ObjectId("56c54be6f96c51370294f123"),
                "name" : "xxxx",
                "photo":null

            }
        }
    ]

I want to update name and photo for this Id author.id:"56c54be6f96c51370294f123".

I wrote the code like this:

    Event.find({'comments.author.id':_id},(err,event)=>{
      _.each(event,function(eventData){

         _.each(eventData.comments,function(commentData){

            if(commentData.author.id == _id){
                 var data={'name':username,'photo':photoUrl};

                Event.update({'commentData.author.id':_id},
{"$set":{"eventData.comments.author":data}},(err,commentupdate)=>{
                          console.log("commentupdate:"+JSON.stringify(commentupdate))
              })
            }
        })
     })
    })

But I am unable to update the data please give me any suggestions. Thanks

Mahesh
  • 395
  • 1
  • 2
  • 18

1 Answers1

0

You can do the update using the $ positional operator and applying the $set operator. The $ positional operator will identify the correct element in the array to update without explicitly specifying its position, thus your final update statement should look like:

Event.update(
    { "comments.author.id": _id }, 
    { "$set": {
            "comments.$.author.name": username,
            "comments.$.author.photo": photoUrl
        }
    },
    (err, commentupdate)=>{
        console.log("commentupdate:" + JSON.stringify(commentupdate))
    }
)
chridam
  • 100,957
  • 23
  • 236
  • 235
  • @ chridam: Thanks for your response, I already tried it but getting response in console like commentupdate:{"ok":1,"n":0,"nModified":0}. – Mahesh Apr 28 '16 at 12:08
  • Can you show how your `Event` model schema is exactly defined? – chridam Apr 28 '16 at 12:20
  • @ chridam: please refer this link actually I want like this http://stackoverflow.com/questions/36917072/how-to-update-multiple-records-in-same-array-in-a-single-collection-in-mongodb – Mahesh Apr 28 '16 at 14:11