无法删除帖子评论:接口返回成功但数据库未删除
问题描述
我认为控制器中的删除评论函数逻辑无误,但调用接口后,Postman返回"Comment deleted successfully!",然而数据库内的评论仍存在,未被删除。请帮忙排查代码问题。
路由代码
router.delete("/:id/comment/:cid", protectRoute, deleteComment);
控制器代码
const deleteComment = async(req, res) => { try { const post = await Post.findById(req.params.id); const comment = post.comments.find( (comment) => comment._id.toString() === req.params.cid.toString() ); if(!comment){ return res.status(404).json({ error: "Comment not found!" }); } if(comment.userId.toString() !== req.user._id.toString()){ return res.status(401).json({ error: "Unauthorized to delete comment" }); } if (comment.userId.toString() === req.user._id.toString()) { post.comments = post.comments.filter( ({ id }) => id !== req.params.cid ); } await post.save(); return res.status(200).json({ message: "Comment deleted successfully!" }); } catch (err) { res.status(500).json({ error: err.message }); } };
Post模型代码
import mongoose from "mongoose"; const ObjectId = mongoose.Types.ObjectId; const postSchema = mongoose.Schema({ postedBy: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true }, text: { type: String, maxLength: 500 }, img: { type: String, }, video: { type: String, ref: "Upload" }, likes: [{ // 存储用户ID数组 type: mongoose.Schema.Types.ObjectId, ref: "User", default: [] }], saves: [{ // 存储用户ID数组 type: mongoose.Schema.Types.ObjectId, ref: "User", default: [] }], comments: [ { id: { type: ObjectId, }, userId: { type: mongoose.Schema.Types.ObjectId, ref: "User", required: true }, text: { type: String, required: true }, likes: [{ // 存储用户ID数组 type: mongoose.Schema.Types.ObjectId, ref: "User", default: [] }], userProfilePic: { type: String, }, username: { type: String }, date: { type: Date, default: Date.now() }, replies: [{ id: { type: ObjectId, }, userId: { type: mongoose.Schema.Types.ObjectId, ref: "User", required: true }, text: { type: String, required: true }, userProfilePic: { type: String, }, username: { type: String }, date: { type: Date, default: Date.now() } }] } ] }, {timestamps: true} ) const Post = mongoose.model('Post', postSchema); export default Post;
问题排查与修复
核心问题出在评论过滤时的类型不匹配,以及查找逻辑的字段一致性问题:
字段匹配不一致:控制器中查找评论时用了
comment._id,但你的Post模型里评论子文档的业务标识是自定义的id字段。虽然MongoDB子文档默认会生成_id,但你接口传参的cid对应的是自定义id,所以查找逻辑应该改为匹配comment.id。类型比较错误:过滤评论时,
id是ObjectId类型,而req.params.cid是字符串类型,直接用!==比较永远为true,导致没有评论被过滤。需要将id转为字符串后再和cid比较。冗余判断:前面已经判断过
comment.userId !== req.user._id时会返回权限错误,后面的if (comment.userId.toString() === req.user._id.toString())判断完全多余,可以直接执行过滤逻辑。
修复后的控制器代码:
const deleteComment = async(req, res) => { try { const post = await Post.findById(req.params.id); // 改为匹配自定义的id字段 const comment = post.comments.find( (comment) => comment.id.toString() === req.params.cid.toString() ); if(!comment){ return res.status(404).json({ error: "Comment not found!" }); } if(comment.userId.toString() !== req.user._id.toString()){ return res.status(401).json({ error: "Unauthorized to delete comment" }); } // 去掉冗余判断,直接过滤,同时将id转为字符串比较 post.comments = post.comments.filter( (comment) => comment.id.toString() !== req.params.cid.toString() ); await post.save(); return res.status(200).json({ message: "Comment deleted successfully!" }); } catch (err) { res.status(500).json({ error: err.message }); } };
另外,建议你在创建评论时确保id字段被正确赋值为新的ObjectId,否则查找和过滤逻辑会失效。比如创建评论时:
// 示例:添加评论时的id赋值 post.comments.push({ id: new mongoose.Types.ObjectId(), userId: req.user._id, text: req.body.text, // 其他字段... });
内容的提问来源于stack exchange,提问作者khayal
相关产品推荐
相关产品推荐

