Thee app.get rout is to display the post content where I have a delete button from which I want to delete the specific post and render back to home route but unable to perform that task please help
//This is the app.js code in which I think the error sustain in delete part
app.get("/posts/:postId", function (req, res) {
let requestedPostId = req.params.postId;
Post.findOne({ _id: requestedPostId }, function (err, post) {
res.render("post", {
title: post.title,
content: post.content,
});
});
});
app.delete("/posts/:postId", function (req, res) {
Post.deleteOne({ _id: req.params.postId }, function (err) {
if (!err) {
res.send("SuccesFully Deleted this Post");
} else {
res.send(err);
}
});
});
// This the the ejs file containing the delete button
<form class="delete" action="/posts/:postId" method="delete">
<button class="btn btn-danger delete-btn" type="submit">
<a class="delete-btn-a" href="/">Delete this Blog</a></button>
</form>
I used the post route under which I used the deleteOne property of MongoDB
app.post("/posts/:postId/delete", function (req, res) {
Post.deleteOne({ _id: req.params.postId }, function (err) {
if (err) {
res.send(err);
} else {
console.log("SuccesFully Deleted this Post");
res.redirect("/");
}
});
});
The issue was in my ejs file in which I was not using the ejs syntax to get the post Id for operation
<form class="delete" action="/posts/<%=postId%>/delete" method="POST">
<button class="btn btn-danger delete-btn" type="submit" title="Delete this blog">
<a class="btn-a"><i class="bi bi-trash"></i></a>
</button>
</form>
I Hope Whosever is reading this post will understand if any issue you can comment on and ask I will be pleased to solve the issue