Open anandkunalmishra opened 1 year ago
when I am running on postman , the json I am using is correct but it showing status 500 means I think await post.delete() not working
Potential Solutions and Suggestions
Post Existence Verification:
Ensure that the Post.findById(req.params.id)
call returns a valid post object. If it returns null or undefined, it might indicate an issue with the ID or the post's non-existence.
Error Handling: Verify that the error handling within the nested try...catch block accurately captures any potential errors thrown during the deletion process.
Mongoose Model Method:
Confirm that the post object retrieved by Post.findById()
supports the .delete()
method. For MongoDB/Mongoose, it might be necessary to use methods like .remove()
or deleteOne()
instead.
Here's an updated version of the code that considers these points:
router.delete("/:id", async (req, res) => {
try {
const post = await Post.findById(req.params.id);
if (!post) {
return res.status(404).json({ message: "Post not found" });
}
if (post.username === req.body.username) {
try {
console.log("Executing try block");
await post.remove(); // Or use post.deleteOne() if appropriate
res.status(200).json({ message: "Post has been deleted" });
} catch (error) {
res.status(500).json({ message: "Error deleting post", error });
}
} else {
res.status(401).json({ message: "You can delete only your post" });
}
} catch (error) {
res.status(500).json({ message: "Server error", error });
}
});
Please ensure that the provided req.params.id
and req.body.username
match the expected data types and values. Also, validate the Mongoose model's method used for deletion according to your schema setup.
Check your server logs or console for any error messages or logs generated during the request for further debugging.
Let me know if you need further assistance or clarification on this matter!
Notes
Please delete this section after reading it
If you have a problem with an error message:
Error output
await post.delete(); not working
My Code