Technical

How to create REST Apis Using NodeJs , Express Js and MongoDB

Description of the image

In this article, we will learn how to create REST APIs using Nodejs, express js, and taking using MongoDB as a database. Before we start let us clarify what we will explore in this particular article
We will explore all CRUD (create, read, update, and delete) operations in MongoDB.
We will also explore how to set up the MVC (model, view, and controller) pattern in our app.
So let's get started….

Folder Structure Setup for REST APIs

Create a new folder named express-rest-api and run the following command npm-init -y and after this create a new file named server.js and now create the following folders Controllers, Models, View, and Routes after that we will have to install the following dependencies.

npm i express nodemon dotenv mongoose. 

SunAug202023Screenshot 2023-08-19 at 10.03.11 PM.png

Explaining Dependencies for REST APIs

Mongoose:  For Operation on MongoDB
Nodemon: It will restart our app automatically when we will save the file or create new files.
Express: Framework of Nodejs we will use for REST APIs.
Dotenv: for managing our app environment.

Setup Environment

For environment setup, we need to create a .env file in our project root directory and we will create 2-3 environment variables.

APP_PORT= We will configure the app port by which it will run 3000.
MONGODB_URI = Here we will paste our MongoDB connection string
APP_ENV = This is our app mode, it can be development or production

SunAug202023Screenshot 2023-08-20 at 8.07.40 PM.png

 

Setup Database for REST APIs 

For database connection, we will create a new folder named Database and in which we will create new file db.js and we will use MongoDB URI from our environment setup.

SunAug202023Screenshot 2023-08-20 at 8.14.25 PM.png

Setup Server.js

Now we set up for server.js file and started to create REST APIs. we will use Express and int our app, we can work through by following the code and screenshot.
And after setuping server.js we can run our app.

SunAug202023Screenshot 2023-08-20 at 8.20.01 PM.png

As now we can see our app is running on PORT 3000 and the database is connected.

Create Model

We will create a new file in the Models Folder named UserModel. So here we will create a UserModel in which we will define some fields which will be necessary For user details like UserName, UserEmail, UserAge, and UserDateofBirth. So let's create it.

SunAug202023Screenshot 2023-08-20 at 8.48.35 PM.png

Create Controller

Here we will create a controller in which we will define some functions by which we can perform our CRUD operations for USERS so let's create it.
Create a new file in the Controllers folder named UserController.

SunAug202023Screenshot 2023-08-20 at 8.56.37 PM.png

With this function, we can insert users into our database. Now it's time for testing but for testing, we need Postman in which we can send JSON data. But before testing we need to define our routes and that we will be our endpoints.

Create Routes

Here we will create a new file in Routes Folder named UserRoutes.

userController.png

So here we have defined routes and now we will import routes in Server.js
For import, we will use the fs(file system) module.

server.js.png

Here at line, number 17 we have imported the routes and all routes can be hit by 
API/then your routes. Now let's go to POSTMAN and create a User.

SunAug202023Screenshot 2023-08-20 at 9.24.06 PM.png

Now the user is created.

CRUD Operations

Now we have completed the create operation let's complete all left operations.

Read:

Here we will read the user's details from the database so first create a controller

crud.png

Routes:


Routes for Getting Users

getRoutes.png

SunAug202023Screenshot 2023-08-20 at 9.24.06 PM.png

Update:


Here we will update the user's details from the database so first create a controller. For updating users we will take user-id in query and update data according to that.

Routes:

SunAug202023Screenshot 2023-08-20 at 9.32.48 PM.png

User Updated Successfully.

Delete: 

Here we will delete the user's details from the database so first create a controller.

userdelete.png

Now the User is Deleted.

Code - REST APIs

Controller

const UserModel = require('../Models/UserModel');

const UserController = {
    async createUser(req, res, next) {
        try {
            const response = await new UserModel(req.body).save();
            if (response)
                return res.json({ status: 200, data: response });
            else
                return res.json({ status: 400 });
        }
        catch (err) {
            console.log(err)
        }
    },
    async getUsers(req, res, next) {
        try {
            const response = await UserModel.find();
            if (response)
                return res.json({ status: 200, data: response });
            else
                return res.json({ status: 400 });
        }
        catch (err) {
            console.log(err)
        }
    },
    async updateData(req, res, next) {
        try {
            const response = await UserModel.findById({ _id: req.query.userID }, req.body, { new: true });
            if (response)
                return res.json({ status: 200, data: response });
            else
                return res.json({ status: 400 });
        }
        catch (err) {
            console.log(err)
        }
    },
    async deleteUser(req,res,next){
        try {
            const response = await UserModel.findByIdAndDelete({ _id: req.query.userID });
            if (response)
                return res.json({ status: 200, data: response ,message:'User Deleted'});
            else
                return res.json({ status: 400 });
        }
        catch (err) {
            console.log(err)
        }
    }
}

module.exports = UserController;

Database

const dotenv = require('dotenv');
const mongoose = require('mongoose');
dotenv.config();

mongoose.connect(process.env.MONGODB_URI, { useNewUrlParser: true, useUnifiedTopology: true });
const db = mongoose.connection;

// Database Connection
try {
  db.on('error', console.error.bind(console, 'Connection Error'));
  db.once('open', () => {
    console.log('Database Connected');
  });
} catch (err) {
  console.log(err, 'ERROR');
}

module.exports = db;

Models

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const UserSchema = new Schema({
    UserName: {
        type: String,
        required: true
    },
    UserEmailAddress: {
        type: String,
        required: true
    },
    UserAge: {
        type: String,
        required: true
    },
    UserDateOfBirth: {
        type: String,
        required: true
    },
    UserStatus: {
        type: String,
        default: 'Active'
    },
    isDeleted: {
        type: Boolean,
        default: false
    }
}, { timestamps: true });

module.exports = mongoose.model('UserSchema', UserSchema, 'UserSchema');

Routes

const express = require('express');
const router = express.Router();

const UserController = require('../Controllers/UserController');


router.post('/user/register', UserController.createUser);
router.get('/user/data', UserController.getUsers);
router.put('/user/update', UserController.updateData);
router.delete('/user/delete', UserController.deleteUser);

module.exports = router;

Server.Js

const express = require('express');
const app = express();
const { readdirSync } = require('fs');

// Import Database Connection
const db = require('./Database/db');
//Import Enviroment Variables
const dotenv = require('dotenv');
dotenv.config();

const APP_PORT = process.env.APP_PORT || 3000;
app.use(express.json());
app.use(express.urlencoded({ extended: false }));


// API ROUTES
readdirSync('./Routes').map((route) => app.use('/api', require(`./Routes/${route}`)));

app.listen(APP_PORT, () => {
    console.log(`Server Started At PORT ${APP_PORT}`);
});

Package.json

{
  "name": "express-rest-api",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start":"nodemon server.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "dotenv": "^16.3.1",
    "express": "^4.18.2",
    "mongoose": "^7.4.3",
    "nodemon": "^3.0.1"
  }
}

Conclusion - REST APIs

So from the above article, we learned how we can perform the CRUD operation in Nodejs and create REST APIs we also explore how to build an app on the MVC Platform and make use of our code look cool. 
Learn more about the node js libraries 

Read More

https://scribblersden.com/article/how-to-host-nodejs-app-on-aws

Follow us on

https://www.linkedin.com/company/scribblers-den

https://www.facebook.com/scribblersden.blogs

Table of Contents

    Leave a reply

    Subscribe to Us

    Always Get Notified