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

Node.js后端删除帖子评论抛出Comment not found错误该如何修复?

问题修复方案

你的代码有两个核心错误导致匹配不到评论:

  • 类型不匹配导致评论查找失败:MongoDB 中存储的评论 _id 是 ObjectId 类型的对象,而 req.params.comment_id 是字符串类型,直接用 === 全等判断会因为类型不一致返回 false,所以永远触发 Comment not found 错误。
  • 字段名错误导致过滤失效:你在过滤评论的时候用的是 id 字段,但是你定义的 Post 模型中没有给 comments 子文档配置自定义 id,默认子文档主键是 _id,就算前面匹配到评论,后续过滤也无法正确删除对应条目。

修复后的控制器代码

export const deleteComment = asyncHandler(async (req, res) => {
  const post = await Post.findById(req.params.id);
  // 额外补充:先判断帖子是否存在,避免后续访问post.comments报错
  if (!post) {
    res.status(404);
    throw new Error('Post not found');
  }

  // 用ObjectId自带的equals方法判断,也可以选择把_id转成字符串比较:comment._id.toString() === req.params.comment_id
  const comment = post.comments.find(
    (comment) => comment._id.equals(req.params.comment_id)
  );

  if (!comment) {
    res.status(404);
    throw new Error('Comment not found');
  }

  // 校验用户权限
  if (comment.user.toString() === req.user._id.toString()) {
    // 过滤时用_id字段比较,同样用equals或者转字符串
    post.comments = post.comments.filter(
      (comment) => !comment._id.equals(req.params.comment_id)
    );

    await post.save();

    return res.json(post.comments);
  } else {
    res.status(401);
    throw new Error('User not authorized');
  }
});

修改完成后再用Postman测试即可正常删除评论。

内容的提问来源于stack exchange,提问作者dev_Dragon

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 06:06:03