Get method API in Nodejs

firstly create the users collection and save all documents.


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},
]

var MongoClient = require('mongodb').MongoClient;
let url="mongodb://localhost:27017/databaseName";
MongoClient.connect(url, function (err, db) {

db.collection("users").insertMany(users, function(err, res) {
    if (err) throw err;
    console.log("all documents are inserted");
    db.close();
  });

 });

Create the get method API to get all documents from the MongoDB


var express = require('express');
var app = express();
var MongoClient = require('mongodb').MongoClient;

app.get('/userList', function (req, res) {

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

    if(!err){

    db.collection("users").find().toArray(function(err, result) {

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

   res.json({data:result,messages:"users list show successfully",status:200})

    db.close();
  });

  }else{

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

});

});

if you need the details of the specific user


var express = require('express');
var app = express();
var MongoClient = require('mongodb').MongoClient;
app.get('/user/:id', function (req, res) {

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

    if(!err){
    
    let req_params=req.params;
    let user_id=(typeof req_params.id !== 'undefined') ? (req_params.id):0;
 
    db.collection("users").find({_id:user_id}).toArray(function(err, result) {

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

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

    db.close();
  });

  }else{

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

});

});

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