如何用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)) }) } }) }) }) 

但是我无法更新数据,请给我任何build议。 谢谢

您可以使用$位置运算符并应用$set运算符来执行更新。 $位置操作符将识别数组中正确的元素进行更新,而不显式指定其位置,因此您的最终更新语句应如下所示:

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