我正确地完成了控制器中的功能(正如我所认为的),但是我无法删除 comments ,即使postman 返回响应" comments 删除成功!"
当我转到数据库时,我发现该 comments 存在于数据库中,并且没有被删除.
我想知道代码出了什么问题.这使得删除过程没有按应有的方式进行.
comment route个
router.delete("/:id/comment/:cid", protectRoute, deleteComment);
controller个
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 });
}
};
my Post Model个
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: [{
// array of user id's
type: mongoose.Schema.Types.ObjectId,
ref: "User",
default: []
}],
saves: [{
// array of user id's
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: [{
// array of user id's
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;