Put method Api in Nodejs

Create the PUT method API to update the document in the MongoDB
Suppose, You have users collection which has three fields
1) _id
2) name
3) email


let users=[
{_id:1,name:"Rom",age:30},
{_id:2,name:"Tony",age:31},
{_id:3,name:"Peter",age:32},
{_id:4,name:"Andrew",age:33},
{_id:5,name:"Symonds",age:34},
{_id:6,name:"John",age:35},
{_id:7,name:"Ponting",age:36},
]

PUT method API code


var MongoClient = require('mongodb').MongoClient;
var express = require('express');
var app = express();
app.put('/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_email=(typeof req_body.email !== 'undefined') ? (req_body.email).trim():"";
   

    let user_details={
    "name":user_name,
    "email":user_email
    }

    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.