I am learning to create a website that allows users to post blogs, users to comment on the blogs and users to reply to those comments. I have used replies[this] in the comment schema to deal with replies to comments. But I am having trouble being able to allow the user to delete these replies. Here is my server side code to delete comments and replies.
// Delete a specific comment or reply
app.get('/deleteComment/:postId/:commentId', requireLogin, async (req, res) => {
try {
const currentUser = req.user;
const { replyId } = req.query;
const foundPost = await Post.findById(req.params.postId);
if (replyId) { // If it's a reply
const comment = foundPost.comments.id(req.params.commentId);
const reply = comment.replies.id(replyId);
// Check if the user is the author of the reply
if (reply.commentUser.toString() !== currentUser._id.toString()) {
return res.status(403).send('Permission denied: You can only delete your own replies.');
}
reply.remove();
} else { // It's a top-level comment
const comment = foundPost.comments.id(req.params.commentId);
// Check if the user is the author of the comment
if (comment.commentUser.toString() !== req.user._id.toString()) {
return res.status(403).send('Permission denied: You can only delete your own comments.');
}
comment.remove();
}
await foundPost.save();
res.status(200).send('Deleted successfully');
} catch (err) {
console.log(err);
res.status(500).send("An error occurred");
}
});
Here is my front end,
<a href="#" onclick="deleteComment('{{../post._id}}', '{{_id}}')">
<i class="fa fa-trash post-icons"></i>
</a>
function deleteComment(postId, commentId) {
const xhr = new XMLHttpRequest();
xhr.open('GET', `/deleteComment/${postId}/${commentId}`, true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
location.reload();
} else if (xhr.status === 403) {
alert('Permission denied: You can only delete your own comments.');
} else {
alert('An error occurred while deleting the comment.');
}
}
};
xhr.send();
}
Replies are stored as objects in an array inside the comments array in mongoose
comments: Array
0: Object
commentUser ObjectId: 650
commentBody: “Hello World”
dateCreated: 2023
replies: Array
0: Object
commentUser: Object
commentBody: “Hello World Replies”
dateCreated: 2023
Every time I try to delete a reply, I get 404 errors. I can delete comments, its just replies. I have tried numerous thing like changing routes and functions to include replyId but it just keeps giving the 404 error. Any ideas why its not working?
I have tried numerous thing like changing routes and functions to include replyId.