karina ivanova
karina ivanova

Reputation: 23

Create a button that DELETES an item from MongoDB (Mongoose Node.js express.js)

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' class="btn btn-lg">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

Upvotes: 0

Views: 1508

Answers (1)

sina-heisenberg
sina-heisenberg

Reputation: 570

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('/')
});

Upvotes: 1

Related Questions