You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
node version: <run "node -v" in you terminal and replace this>
npm version: <run "npm -v" in you terminal and replace this>
os: windows 7/windows 10/mac/linux
Error output
// copy your error output here
await post.delete(); not working
My Code
// copy your code hererouter.delete("/:id",async(req,res)=>{try{constpost=awaitPost.findById(req.params.id);if(post.username===req.body.username){try{console.log("executing try block ");awaitpost.delete();res.status(200).json("Post has been deleted ...");}catch(error){res.status(500).json(error);}}else{res.status(401).json({message:"You can delete only your post "});}}catch(error){res.status(500).json(error);}});
The text was updated successfully, but these errors were encountered:
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
The text was updated successfully, but these errors were encountered: