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




Hey guys, in our previous post we discussed about retrieving the documents from mongodb using GET request. so in this post we will discuss that updating the document using PATCH request. let’s begin…

To update the document, mongoose provides methods like update(), updateOne() and findByIdAndUpdate(). In this post we will discuss about the findByIdAndUpdate(). So as the name suggests, we will pass an document id which we need to update and the updated object. findByIdAndUpdate() returns Query object.

Let’s look at the example..

router.patch('/blogs/:id', (req, res) => {
    Blog.findByIdAndUpdate(req.params.id, req.body, {new: true}).then((blog) => {
        if (!blog) {
            return res.status(404).send();
        }
        res.send(blog);
    }).catch((error) => {
        res.status(500).send(error);
    })
})

If you look at the 3rd parameter, which is options. we are going to set new to true, which means By default, findByIdAndUpdate() returns the document as it was before update was applied. If you set new: true, findOneAndUpdate() will instead give you the object after update was applied

Let’s update the first object

findByIdAndUpdate()


Parameters:

  • id, document object which we need to update
  • document, updated object/document
  • options optional
  • callback function

returns Query object

That’s it for this post, in the next post we will discuss about other methods like update() and updateOne()


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. Dean

    Hi Bushan Sirgur! thanks for your explanation…
    But i still have a question in mind ?

    How can i implement patch request for my UserModel since if i throw the whole req.body it can be very dangerous, i.e someone can add password in the body and that’s it i got hacked… So… how can i implement this with more security?

Leave a Reply