NodeJS, Express, Mongoose and MongoDB RESTful Web Service – DELETE Request





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 delete
  • options, optional parameter
  • callbackfunction

It will return Queryobject

That’s all about this post, in the next post we will discuss about the other methods like deleteOne(), deleteMany() findOneAndDelete()



Bushan Sirgur

Hey guys, I am Bushan Sirgur from Banglore, India. Currently, I am working as an Associate project in an IT company.

This Post Has One Comment

  1. Theda

    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!

Leave a Reply