Reputation: 21
I am using mongoose in this example. While trying to delete ,the following error is being shown to me
Cannot DELETE /5e69e2fde0fa464ee01dd68d
I cannot for the life of me figure out what is going wrong .I am a complete beginner in Node.js , MongoDB and creating RESTful APIs The code given below is the function I am using to delete .
router.delete('/:id', getSubscriber, async (req, res) => {
try {
await res.subscriber.remove()
res.json({ message: 'Deleted Subscriber' })
} catch (err) {
res.status(500).json({ message: err.message })
}
})
and here is the getSubscriber function
async function getSubscriber(req, res, next) {
let subscriber
try {
subscriber = await Subscriber.findById(req.params.id)
if (subscriber == null) {
return res.status(404).json({ message: 'Cannot find subscriber' })
}
} catch (err) {
return res.status(500).json({ message: err.message })
}
res.subscriber = subscriber
next()
}
Any help is appreciated. Thank you for your time.
Upvotes: 1
Views: 315
Reputation: 1722
router.delete('/:id', getSubscriber, async (req, res) => {
try {
//Here try creating an instance of your model.
//I think your schema is named subscriber so
const deleteSuscriber = await Suscriber.remove({_id:req.params.id});
res.json(deleteSuscriber);
} catch (err) {
res.status(500).json({ message: err})
}
});
Here express will put the variable in req.params form the incoming request.
Hope this works!!
Here you can find the documentation on making CRUD Rest API
Upvotes: 1