2016-04-28 35 views
2

我想更新數組中的子字典。如何用Mongodb中的子字典更新數組

我的數組這樣

"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 

      } 
     } 
    ] 

我要爲這個ID author.id:"56c54be6f96c51370294f123"更新的名字和照片

我寫了這樣的代碼:

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)) 
       }) 
      } 
     }) 
    }) 
    }) 

但我無法更新數據,請給我任何建議。謝謝

回答

0

您可以使用$ positional operator並應用$set運算符來執行更新。該$ positional operator將確定數組中正確的元素沒有明確指定其位置更新,因此您的最終更新語句應該是這樣的:

Event.update(
    { "comments.author.id": _id }, 
    { "$set": { 
      "comments.$.author.name": username, 
      "comments.$.author.photo": photoUrl 
     } 
    }, 
    (err, commentupdate)=>{ 
     console.log("commentupdate:" + JSON.stringify(commentupdate)) 
    } 
) 
+0

@ chridam:感謝您的回覆,我已經嘗試過,但得到的控制檯響應like commentupdate:{「ok」:1,「n」:0,「nModified」:0}。 – Mahesh

+0

你能說明你的'Event'模型模式是如何精確定義的嗎? – chridam

+0

@ chridam:請參考這個鏈接其實我想要這個http://stackoverflow.com/questions/36917072/how-to-update-multiple-records-in-same-array-in-a-single-collection-in -mongodb – Mahesh