【问题标题】:Is it possible to find a specific element in a subarray by ID and edit only that element?是否可以通过 ID 在子数组中找到特定元素并仅编辑该元素?
【发布时间】:2019-09-02 18:20:20
【问题描述】:

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

是否无论如何都可以查询和编辑文档中子数组中的特定元素?

所以它会变成这样,

const newComment = {...};

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

comment.push(newComment);

await comment.save();

我想要完成此操作的原因是因为 cmets 嵌套在 Post 架构中。如果我可以返回评论,用评论 ID 指定,并循环浏览所有喜欢的评论,那会更有效率。而不是在allPost 的 cmets 中循环,然后然后在所有喜欢的位置中循环。

【问题讨论】:

    标签: mongodb mongoose


    【解决方案1】:

    你可以使用下面的方法,

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-04-04
      • 2018-09-16
      • 1970-01-01
      • 2022-09-28
      • 2013-09-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多