I have a CRUD project where a user can insert data with forms and it's all stored in mongoDB. Everything seems to work fine but I can't find a solution on how to create a button that deletes a specific item from a DB.
//Code for Delete button (which is within the article when you click on it)
<form action="/delete/:id" method="post">
<button type='submit' >Delete</button>
</form>
//This is my solution so far
app.post('/delete/:id', (req, res) => {
Post.deleteOne((err) => {
if (!err) {
res.redirect('/')
}
})
});
So the problem is when I click Delete, it deletes the first item from the DB. I need it to delete the page where I clicked the button on.
before Delete ||| after Delete
CodePudding user response:
First things first, check if a provided ID is the actual object ID then you must pass that ID into the command:
app.post('/delete/:id', async (req, res) => {
await Post.deleteOne({_id: req.params.id})
return res.redirect('/')
});