gpt4 book ai didi

node.js - 如何将新元素推送到子文档中“发布”>“评论”>“回复”>“喜欢”作为数组

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

我有一个示例 Post 集合

[{
"_id" : ObjectId("5da832caeb173112348e509b"),
"body" : "Lorem Ipsu.",
"comments" : [
{
"comment" : "my sample comment",
"_id" : ObjectId("5db06e11d0987d0aa2cd5593"),
"replies" : [
{
"likes" : [
"5d999578aeb073247de4bd6e",
"5da85558886aee13e4e7f044"
],

"_id" : ObjectId("5db6a88f7c6cfb0d0c2b689b"),
"reply" : "my reply to this comment",
"user" : "5da85558886aee13e4e7f044"
}
],

"likes" : [
"5da85558886aee13e4e7f044",
]
},

],

}]

要将添加删除元素添加到comments.likes中,我可以这样做,$push$pull,它适用于以下操作。

   Post.updateOne(
{_id: req.body.id_post, "comments._id": req.body.id_comment},
{ $push: {"comments.$.likes": req.user._id}});

但是如果我想pushreplies.likes,有人可以帮助指导我吗?

我尝试过类似的操作,但 replies.likes 未更新。

 db.posts.updateOne(
{ "comments.replies._id": Object("5db6a88f7c6cfb0d0c2b689b") },
{ "$push": { "comments.0.replies.$.likes": Object("5db6a88f7c6cfb0d0c2b689a") } },
function(err,numAffected) {
// something with the result in here
}
);

最佳答案

您可以使用数组过滤器:

db.getCollection("test").updateOne(
{
"comments.replies": {
"$elemMatch": {
"_id": Object("5db6a88f7c6cfb0d0c2b689b")
}
}
},
{ "$set": { "comments.$[outer].reply.$[inner].likes": Object("5db6a88f7c6cfb0d0c2b689a") } },
{
"arrayFilters": [
{ "outer._id": ObjectId("5cd26a886458720f7a66a413") },
{ "inner._id": ObjectId("5cd26a886458720f7a66a415") }
]
}
)

不介意 ID

关于node.js - 如何将新元素推送到子文档中“发布”>“评论”>“回复”>“喜欢”作为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58590163/

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