繁体   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