0

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

2
  • It does not deliver the ID received as params to MongoDB. Add a filter to the first parameter of deleteOne. Commented Feb 14, 2022 at 10:40
  • Do this Post.deleteOne({_id: req.params.id}, (err) => { ... Commented Feb 14, 2022 at 10:43

1 Answer 1

1

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('/')
});
Sign up to request clarification or add additional context in comments.

5 Comments

Could you please mark it as accepted?
For delete HTTP requests use app.delete(...).
I get this error here.. const castError = new CastError(); ^ CastError: Cast to ObjectId failed for value ":id" (type string) at path "_id" for model "Post"
if you could, please take a look at my code. Maybe you'll see what I'm doing wrong. Thanks in advance! github.com/karina4840/daily-journal-site-4840
This error happens if the provided ID is not valid object ID please validate that using this method: var ObjectId = require('mongoose').Types.ObjectId; ObjectId.isValid(<PASS YOU ID HERE>);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.