Patch method Api in Nodejs

patch method is used when you want to update the resource like update the name, status etc. patch method is faster than put method. put method basically used when you want to change the whole resource value.

Create the patch method API to update the document in the MongoDB

var express = require('express');
var app = express();
app.patch('/updateUser/:id', function (req, res) {

    MongoClient.connect(url, function (err, db) {

    if(!err){

    let req_params=req.params;
    let req_body=req.body;

    let user_id=(typeof req_params.id !== 'undefined') ? (req_params.id):0;
    let user_name=(typeof req_body.name !== 'undefined') ? (req_body.name).trim():"";

    let user_details={
    "name":user_name
    }

    db.collection("users").UpdateOne({"_id":user_id},{$set:user_details},function(err, result) {

    if (err){
      res.json({data:result,messages:"some thing went wrong",status:501})
    }

   res.json({data:result,messages:"user update successfully",status:200})

    db.close();
  });

  }else{

   res.json({data:err,messages:"some thing went wrong",status:501})
  }

});

});

Note:- In the above example req.body is used to get the URL body parameters value and req.params is used to get the route parameters value.