首页 > 解决方案 > 是否可以通过 ID 在子数组中找到特定元素并仅编辑该元素?

问题描述

我发现这个答案认为它解决了我的问题,直到我意识到查询返回整个父文档。

无论如何要查询和编辑文档中子数组中的特定元素吗?

所以它会像,

const newComment = {...};

const comment = await Post.find({comments: ObjectId("50ae3bdb50b3d6f014000279")})

comment.push(newComment);

await comment.save();

我想完成这个的原因是因为注释嵌套在Post模式中。如果我可以返回评论,用评论 ID 指定,并循环浏览所有喜欢的评论,那会更有效率。而不是循环浏览的所有评论Post然后循环浏览所有喜欢的东西。

标签: mongodbmongoose

解决方案


您可以使用以下方法,

const newComment = {...};

Post.find( { "comments": "50ae3bdb50b3d6f014000279" } )
.exec((err , foundComment) => {
   if(err){
      console.log(err)
   }else{
     foundComment.push(newComment);
     foundComment.save();
   }

});

推荐阅读