REST API – PATCH – to Update some fields only in Mongo DB Record

PATCH request in REST API can be made to update particular fields in a particular record. It can alter certain fields without replacing entire record. Or like the PUT request it does not delete other fields that are not fed inputs. SO we can easily alter the necessary fields of a mongo db record.

Lets check the usage of PATCH request in REST API. Here is the Express JS code for updating the MONGO DB record using PATCH.

Code:

app.route('/articles/:articleTitle').patch(function(req,res){
  Article.updateOne(
    {title: req.params.articleTitle},
    {$set: req.body},
    function(err){
      if(!err){
        res.send("Successfully updated article.");
      }else{
        res.send("failed");
      }
    }
  )
});

About the Author: smartcoder

You might like

Leave a Reply

Your email address will not be published. Required fields are marked *