gpt4 book ai didi

node.js - 如何在 Mongodb 中使用子字典更新数组

转载 作者:太空宇宙 更新时间:2023-11-03 22:31:15 24 4
gpt4 key购买 nike

我想更新数组中的子字典。

我的数组是这样的

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

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

最佳答案

您可以使用 $ positional operator 进行更新并应用 $set运算符(operator)。 $ 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))
}
)

关于node.js - 如何在 Mongodb 中使用子字典更新数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36912838/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com