You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Mongoose向帖子评论数组添加评论后,无法在同函数中获取该评论

问题原因与解决方法

问题1:find({commentId:uuid}) 返回undefined

JavaScript数组的find()方法不支持传入对象作为查询条件,它仅接受回调函数作为参数。用对象调用数组find无法匹配到目标项,因此返回undefined。

问题2:回调式find触发500内部错误

调用postToComment.updateOne()后,当前的postToComment文档实例不会自动更新——它仍然是你通过findById获取的原始数据,comments数组里并没有刚添加的新评论。此时用find查找不存在的commentId,后续依赖该值的操作会引发未处理异常,最终导致500错误。

正确实现方案

方案1:直接修改文档实例并保存(更直观)

无需使用updateOne,直接操作数组后调用save(),文档实例会同步更新,就能直接获取刚添加的评论:

export const commentOnPost = async (req, res) => {
  const uuid = uuidv4();
  try {
    const postToComment = await Post.findById(req.params.postId);
    if (!postToComment) {
      return res.status(400).json({ error: "Post not found" });
    }
    console.log(req.body, "body check ");
    const commentObject = {
      userId: req.userId,
      comment: req.body.comment,
      commentId: uuid,
    };
    // 直接将评论推入数组
    postToComment.comments.push(commentObject);
    // 保存更新后的文档
    await postToComment.save();
    // 此时实例已更新,可找到刚添加的评论
    const postedComment = postToComment.comments.find(
      (comment) => comment.commentId === uuid
    );
    console.log(postedComment, "comment that was posted");

    res
      .status(200)
      .json({ message: "Commented successfully", comment: postedComment });
  } catch (err) {
    res.status(500).json(err);
  }
};

方案2:使用findByIdAndUpdate获取更新后的文档

如果偏好使用更新操作符,可以用findByIdAndUpdate并设置new: true,直接返回更新后的文档:

export const commentOnPost = async (req, res) => {
  const uuid = uuidv4();
  try {
    const commentObject = {
      userId: req.userId,
      comment: req.body.comment,
      commentId: uuid,
    };
    // 更新文档并获取最新版本
    const updatedPost = await Post.findByIdAndUpdate(
      req.params.postId,
      { $push: { comments: commentObject } },
      { new: true, runValidators: true }
    );
    if (!updatedPost) {
      return res.status(400).json({ error: "Post not found" });
    }
    const postedComment = updatedPost.comments.find(
      (comment) => comment.commentId === uuid
    );
    console.log(postedComment, "comment that was posted");

    res
      .status(200)
      .json({ message: "Commented successfully", comment: postedComment });
  } catch (err) {
    res.status(500).json(err);
  }
};

注意:原代码中if (!postToComment)分支未加return,可能导致后续代码继续执行引发错误,上述方案已补充该逻辑。

内容的提问来源于stack exchange,提问作者Abhay Thayyil Mukundan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 13:18:23