簡體   English   中英

Mongoose 在集合內的 object 的嵌套數組中更新 object

[英]Mongoose update an object in a nested array of object inside a collection

我有這個代碼:

const updateComment = async (req, res) => {
  try {
    const post = await Post.findById(req.body.postId);
    const comment = post.comments.find(
      (comment) => comment.id === req.body.commentId
    );

    res.status(200).json(comment);
  } catch (err) {
    console.log(err);
    res.status(500).json(err);
  }
};

由於我不能使用 mongoose findfindById因為它不是集合,所以我使用 javascript find方法來查找特定評論,但由於我不能同時使用updateOne ,我該如何更新評論正文?

我試過這個:

comment.body = req.body.newCommentBody;

但它不起作用,如何變異數據庫中的object?

取決於您是否在所有數據庫中使用唯一的 commentId(如 ObjectId)。 然后您可以使用 updateOne 按評論 ID 搜索並使用位置運算符 $ ,如下所示:

await Post.updateOne(
{"comments.id" : req.body.commentId}, 
{"comments.$.body": req.body.newCommentBody}
) 

但是這樣你就不會得到評論來發送資源。 您還可以找到帖子,就地更新並發送回數據庫:

const post = await Post.findById(req.body.postId)
const comment = post.comments.find(
      (comment) => comment.id === req.body.commentId
    );
comment.body = req.body.newCommentBody
await post.save()

 res.status(200).json(comment);

我不確定 if.findById() 返回數組還是單個文檔,如果數組你當然必須添加[0]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM