How to create a REST API using Mongodb and Express in Nodejs


From the past post we have learned how to create an API for your project using the Nodejs framework Express. If you miss the post please read it first, it may help you understand this tutorial faster.

[posts-display id=3884 include_excerpt=true]

In this tutorial we are going to create a real world REST API which is capable of performing CURD operations on User object.

The Project used the following Nodejs modules and packages

  • Express
  • Mongodb
  • dotevn
  • mongoose

Project Structure

Unlike the first post on Node API I want a structured project to following. So I split the code into four.

  1. Model
  2. Routes
  3. Project Itself (app.js,env)

Model

The model define the structure or Schema. Using the Mongoose package we can easily create schema for Mongodb documents.

const mongoose=require('mongoose')
 const usersSchema=new mongoose.Schema({
     uname:{
     type:String,
     require:true
     },
     role:{
     type:String,
     required:true
     }
 })
 module.exports =mongoose.model('User',usersSchema)

Routes

Routes define the API routes, in which we used the Model to POST,GET,DELETE documents from Mongodb dynamically. We have only one route file called users.js as follows

const express = require("express");
const router = express.Router();
const User = require("../models/user");

router.get("/", async (req, res) => {
 try {
   const users = await User.find();
   res.send(users);
} catch (error) {
   res.status(500).json({ message: error.message }); //500 server side error
}
});
router.get("/:id", getUser, (req, res) => {
     res.send(res.user)
});
router.post("/", async (req, res) => {
 const user = new User({
   uname: req.body.uname,
   role: req.body.role,
});
 try {
   const newUsr = await user.save();
   res.status(201).json(user); //201 - successful
} catch (error) {
   res.status(400).json({ message: error.message }); //400
}
});


router.delete("/:id", getUser, async(req, res) => {
try {
   await res.user.remove()
   res.json({ message: 'Deleted ' }); //400

} catch (error) {
   res.status(500).json({ message: error.message }); //400
}
});

router.patch('/:id',getUser,async(req,res)=>{
   if(req.body.uname!=null){
res.user.uname=req.body.uname
  }

   if(req.body.role!=null){
       res.user.role=req.body.role
          }
           try {
               const updatedUser=  res.user.save()
               res.send(updatedUser)
          } catch (error) {
               res.status(500).json({ message: error.message }); //400
          }
})


async function getUser(req,res,next){
   let user
   try {
       user=await User.findById(req.params.id)
       if(user==null){
           return res.status(401).json({message:'User does not exist'})
      }
  } catch (error) {
       return res.status(401).json({message:error.message})
  }
   res.user=user
   next()
}
module.exports = router;

Routes in the app.js

We can define as many as routes in route folder which can be include in the app.js file using app.use(‘/users’,usersRouter) . The modular structure of routes also help us to easily manage the routes.

require('dotenv').config()
const express=require('express')
const app=express()
const mongoose=require('mongoose')

mongoose.connect(process.env.DATABASE_URL,{useNewUrlParser:true})
const db= mongoose.connection
db.on('error',(error)=>console.log(error));
db.once('open',()=>console.log('Connected to DataBase'))
app.use(express.json())

const usersRouter=require('./routes/users')
app.use('/users',usersRouter)

const port = process.env.PORT || 3000;
app.listen(port,()=>console.log('Server Started'))

dotenv and .env

We are created a .env file to store the configuration for MongoDB the content of the file look like

DATABASE_URL= mongodb://localhost/users

We can use the dotenv module to read the settings from the .env file using process.env

process.env.DATABASE_URL

Mongodb

I have used a local version of Mongodb for store the data. To use a cloud version of Mongo you have to replace the connection string in the environment file (.env file).

How to Test the API

As in the last example we have to use POSTMAN desktop or online version to test the API, also we have to make sure the data is saved in MongoDB, for this MongoDB Compass is a great choice.

The complete project can be located @ GitHub Repository

Published by

Manoj

A developer,teacher and a blogger obsessed with Python,Dart and open source world from India

3 thoughts on “How to create a REST API using Mongodb and Express in Nodejs”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.