I am working on a crud project and I want to delete a item by id using MongoDB, express, and node.
here is the functionality for me to delete an item:
router.get('/delete/:id', async (req, res) => {
try {
const topic = await Topic.findById(req.params.id)
await Topic.remove({ _id: req.params.id })
res.redirect('/dashboard')
} catch (error) {
console.log(error)
}
})
here is the ejs portion for when a user click on the item to be deleted:
<div class="modifyTopic">
<a href="/edit/<% topic._id %>"><i class="fas fa-edit fa-2x"></i></a>
<a href="/delete/<%= topic._id %>"><i class="fas fa-trash fa-2x"></i></a>
</div>
this code actually works but when I change the get method to a delete method like this:
router.delete('/delete/:id', async (req, res) => {
try {
const topic = await Topic.findById(req.params.id)
await Topic.remove({ _id: req.params.id })
res.redirect('/dashboard')
} catch (error) {
console.log(error)
}
})
it do not work. I get a message in the browser saying "Cannot GET /delete/62def4aae6c2c1914cfa145fer3" why is this? I should be using the delete method instead of get right? How can I make this work with the delete approach?