Mongodb 是否可以通过ID在子阵列中查找特定元素并仅编辑该元素?

Mongodb 是否可以通过ID在子阵列中查找特定元素并仅编辑该元素?,mongodb,mongoose,Mongodb,Mongoose,我发现这种想法解决了我的问题,直到我意识到查询返回整个父文档 在文档的子数组中是否有特定元素可以查询和编辑 所以它会有点像 const newComment = {...}; const comment = await Post.find({comments: ObjectId("50ae3bdb50b3d6f014000279")}) comment.push(newComment); await comment.save(); 我想完成这项工作的原因是注释嵌套在Post模式中。如果我

我发现这种想法解决了我的问题,直到我意识到查询返回整个父文档

在文档的子数组中是否有特定元素可以查询和编辑

所以它会有点像

const newComment = {...};

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

comment.push(newComment);

await comment.save();

我想完成这项工作的原因是注释嵌套在
Post
模式中。如果我可以返回注释,用注释ID指定注释,并循环遍历所有类似的注释,那么效率会更高。不要循环浏览
帖子的所有评论,然后循环浏览所有类似的评论。

您可以使用以下方法

const newComment = {...};

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

});

您可以使用以下方法

const newComment = {...};

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

});