Hey guys, in the previous post we discussed about updating the document with HTTP PATCH request. In this post, we will discuss about deleting document with HTTP DELETE request. let’s begin
In order to delete the document from mongodb, mongoose provides several methods like deleteOne()
, findByIdAndDelete()
, findOneAndDelete()
and deleteMany()
. so in this post, we will discuss about deleting document using findByIdAndDelete()
.
As the name suggests, we will pass a document id which we want to delete and this will return a Query
object, on the query object we will call then()
.
Let’s look at an example..
router.delete('/blogs/:id', (req, res) => {
Blog.findByIdAndDelete(req.params.id).then((blog) => {
if (!blog) {
return res.status(404).send();
}
res.send(blog);
}).catch((error) => {
res.status(500).send(error);
})
})
using the req.params
we will get the route parameter.
Let’s delete the second object
Model.findByIdAndDelete()
Parameters:
Id
, document id which we want to deleteoptions
, optional parametercallback
function
It will return Query
object
That’s all about this post, in the next post we will discuss about the other methods like deleteOne()
, deleteMany() findOneAndDelete()
First of all I want to say great blog! I had a quick question in which I’d like
to ask if you don’t mind. I was interested to find out how you center
yourself and clear your mind prior to writing. I have had a difficult time clearing my
mind in getting my thoughts out. I do take pleasure in writing however
it just seems like the first 10 to 15 minutes tend to be lost
simply just trying to figure out how to begin. Any ideas or hints?
Appreciate it!