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
相关产品推荐
相关产品推荐

