MVC Architecture With Node.js CRUD Application [Node.js-Express-MongoDB]

Introduction

Today I'm going to explain an Interesting topic about MVC Application- CRUD operations (create, read, update, and delete) Using [Node.js-Express-MongoDB]. 

I'm going to cover this list.

  1. Introduction of MVC Architecture
  2. Create a Node JS application.
  3. Create Environment Variables.
  4. Create The MongoDB Connection and Connect the App.
  5. MVC Architecture for Node applications.
  6. Create a CRUD Operation.

Let's start Our Topic.

01. Introduction of MVC Architecture


What is a Model-View-Controller?

I'm going to explain a new topic about MVC. 

MVC stands for Model-View-Controller, which is a famous architectural design pattern for building software applications and projects. It’s one of the most popular ways of building web applications, mobile applications, and Desktop applications. It is used majorly by Node developers and by C#, Ruby, and PHP framework users too.  MVC helps developers organize code by separating concerns into three components: 

  1. Model: Represents the data in our application
  2. View: The part of the application that the user interacts with. It represents the UI of your application
  3. Controller: The controller is responsible for most of your business logic.  In a web application, the controller will handle the requests coming into your application. 

Server

Picture 1. Model-View-Controller Architecture.

I’ll explain how the MVC Architecture works step by step, followed by a Picture.

  1. The client will first send a request for the Server.
  2. The controller takes that request and passes it to the model.
  3. The model interacts with the database, and in the process, it also executes some business logic if required.
  4. After getting the data from the database, it will pass to the controller. 
  5. The controller will pass the data to the view.
  6. The View formats the data.
  7.  The format data is sent to the Client.

I explained the basic steps of MVC Architecture with an image. I do not give a big picture for MVC here, I'm going to explain the MVC pattern for the Node.js application. 

Let's start to create a new project.

02. Create a Node JS application

How to create a Node-js application? This Is your first time visiting my articles?  

I already Published the articles here about Node-js. Here, I share the Links.

  1. How to Setup the Node Environment- Introduction of Node.js, Features, Installation Guide and Benefits
  2.  Run a Simple Node Server Project with Express Framework
  3. Node.js RESTful API Project with Express, MongoDB, and Postman. In this article has more features. Are you a beginner in Node-js? I recommend this article to start node-js projects.

Install the node-js

Step 1. Install the Node-js. Here is the link: Download and install Node-js. If Installed, the Node.js check the Node and npm versions following the command.

Node 

Node --version or Node -v

Check the npm version.

npm --version or npm -v

Step 2. Create a new folder for the project. I created a student_api.

Step 3. Open the project folder directory in the vs-code.

Step 4. Open the terminal and open the current folder directory in the terminal.

Create a package.json

Step 5. Run npm init -y  It is To create a package.json file in your project. 

Microsoft Versions

Picture 2.  Here, you can see the project JSON file and field name and descriptions.

Install the npm express, nodemon, body-parser, and mongoose

These npm packages basically need to work with API projects. 

Step 6. Install the Express, nodemon, body-parser, and Mongoose. Here is the link to the npm packages.

  1. Express is a web application framework of node js.
  2. Body-parser. Node.js body parsing middleware.
  3. Nodemon. Node. Js-based applications by auto restarting the node application.
  4. Mongoose. Mongoose is a MongoDB object modeling tool.

I installed npm install express nodemon body-parser mongoose. 04 npm packages.

NPM Package

Picture 3. Here, you can see the student_api package.json. What we installed the packages are added to the dependency

Step 7. Create an index page for the project as  index.js.

const express = require("express");
const app = express();

app.get("/", function (req, res) {
  res.send("Running MVC Application, Student API Project.");
});

app.listen(3000);

Step 8. Add a line in package.json in scripts. Nodemon for automatically restarting the node application

 "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon index.js"
  },

Run the project in npm start.

Index.js

Picture 4. Here, you can see our project run successfully. We use npm start.

Running MVC

Picture 5. Get the output in the browser successfully.

03. Create The MongoDB Connection and Connect the App

How to create a MongoDB Atlas account and MongoDB Connection?  I explained these headings in my previous articles. Here, I share my articles.   

  1. How to Create a MongoDB Atlas Account?
  2. Node.js RESTful API Project with Express, MongoDB, and Postman 

Create The MongoDB Connection.

Basically, I'm going to explain. 

MongoDB Atlas: It is a fully managed cloud database.  It is open-source in nature and is a NoSQL database.  And there are some advantages when used. It's shameless. The structure of a single object is clear, with no complex join and deep query ability.

You’ll need to do the following steps 

  1. Create a MongoDB Cloud account
  2. Create a MongoDB Atlas cluster
  3. Configure network access and create a cluster user
  4. Connect to the cluster

I have explained these steps in the above link How to Create a MongoDB Atlas Account?, I continue from this article.

Step 9. Click the Connect button on the dashboard.

Database Deployment

Picture 6. MongoDBCluster01 is my cluster.

After Clicking on the connection button. appearing in this connection dialog box.

MongoDB Drivers

Picture 7. Now see the dialog box. I highlight the red line box and click the Drivers panel.

Step 10. Click on the Driver panel. You will get MongoDB Driver. Select your driver and version, and Add your connection string to your application code.

Driver Versions

Picture 8. Select your driver as Nodejs and version as the last version.

Step 11. We select the driver and version. After that, you can copy the connection string from the highlight box 02.

Connect the App with MongoDB

Let’s see how to connect to MongoDB. 

We already installed the Mongoose npm package. Mongoose supports Node.js. We can refer to the Mongoose npm site and implement the code here. 

Step 12. Import the Mongoose. Create the Mongoose variable.

// Using Node.js `require()`
const mongoose = require('mongoose');

// Using ES6 imports
import mongoose from 'mongoose';

Connect the DB with the Node application.

mongoose
  .connect(<Past you connection > )
  .then(() => {
    app.listen(3000, () => {
      console.log(`Node API app is running on port 3000`);
    });
  })
  .catch((error) => {
    console.log(error);
  });

app.listen() function is used to bind and listen to the connections on the specified host and port. I set my app to listen to port 3000(You can change your Port for app listen ).

 app.listen(3000, () => {
      console.log(`Node API app is running on port 3000`);
    });

Here you can pass the connection string and  <Username> as your username <Password> db password <DB_Name> you enter the Database name.

"mongodb+srv://<Username>:<Password>@mongodbcluster01.joofg8v.mongodb.net/<DB_Name>?retryWrites=true&w=majority"

Here you can see the code.

mongoose
  .connect( "mongodb+srv://<Username>:<Password>@mongodbcluster01.joofg8v.mongodb.net/<DB_Name>?retryWrites=true&w=majority"
  )
  .then(() => {
    console.log("connected to MongoDB Atlas");
    app.listen(3000, () => {
      console.log(`Node API app is running on port 3000`);
    });
  })
  .catch((error) => {
    console.log(error);
  });

Connect to MongoDB Atlas

Picture 9. Successfully connected the database and running port 3000.  

04. Create Environment Variables

Environment variables are helpful in software development. Environment Variables are variables that are set by the Operating System. In our case, we are learning that Node.js has a lot of great features. One of them features a way of working with environment variables, which many cloud hosts (such as Azure, Google Cloud, AWS, Now. sh, etc.) use. while hosts will set a PORT variable that specifies on which port the server should listen to, modules might have other behaviors depending on the value of the NODE_ENV variable. It can be accessed from applications and programs through various APIs. Why do we need to create Environment variables? It is Security, Flexibility, and Adoption. 

Step 13. Let's create an Environment variable in Node js.

  1.  Go to the npm page and search dotenv. I link the url here. npm i dotenv  Install the npm package for dotenv for your node js application.
  2. Create an env file in node-js. Do not create a js file. Name it .env. 
  3. Now I'm going to move the DB connection for .env from the Server.js. Create a variable name as a MONGO_CONNECTION and paste the DB connection.

MongoDB Connection .env

Picture 10. Now you can see the .env and mongoDB connection.

Step 14. Include the .env in index js for the Node js application.

Go to the index.js file and paste this line as a first “require('dotenv').config()” 

I created a variable for env MONGO_CONNECTION.

const MONGO_CONNECTION = process.env.MONGO_CONNECTION;

Go to the mongoose.connect(paste your env variable).

mongoose
  .connect(MONGO_CONNECTION)
  .then(() => {
    console.log("connected to MongoDB Atlas");
    app.listen(3000, () => {
      console.log(`Node API app is running on port 3000`);
    });
  })
  .catch((error) => {
    console.log(error);
  });

MongoDB Connection

Picture 11. I underline the steps here, We can change the Listen-PORT also the same way

05. MVC Architecture for Student API Project

 

 

Student API Project with MVC

Student Model

Picture 12. Student API Project MVC Architecture

In this scenario, we have three parts (Model, Controller, and Router).

  1. Model: Student Model. 
  2. Controller: Student Controller (Business Logic)
  3. Router /View: Student Route, In the project, I’m not creating a view. I will check the route in POSTMAN.

Step 15. Create models, controllers, and route folders in your project.

Explorer

Picture 13. MVC folder structure is created. 

How To Apply MVC Architecture to our project?

 

 

Create a model

Student

Picture 14. Student Model

Step 16. Create a Student Model. Inside the model's folder, create a studentModel.js.

The model requires a Schema from the Mongoose. Create a Schema first.

  1. Create a variable as a mongoose,  const mongoose = require("mongoose"); That is interactive with the database. We use Mongoose.
  2. Create a studentSchema,  const studentSchema = mongoose.Schema().

const mongoose = require("mongoose");

const studentSchema = mongoose.Schema(
  {
    name: {
      type: String,
      required: [true, "Please enter a Student name"],
    },
    address: {
      type: String,
      required: true,
    },
    dateOfBirth: {
      type: Date,
      required: true,
    },
    gender: {
      type: String,
      required: true,
    },
    phoneNum: {
      type: Number,
      required: false,
    },
  },
  {
    timestamps: true,
  }
);

const Student = mongoose.model("Student", studentSchema);
module.exports = Student;

Inside the schema, create a student model.

Create a variable for studentSchema as a Student in mongoose.model.const Student = mongoose.model("Student", studentSchema);

Student model export. module.exports = Student;

Create a controller

The controller controls the business logic. It receives the user input through the view layer and processes the information through the model layer.

The basic CRUD operation in MVC. Below are the CRUD operations.

CRUD Operation in MVC

Picture 15. Student CRUD operation.

  • Create a Student record in the database.
  • Read all Student's records in the database.
  • Update a Student record in the database.
  • Delete a Student record in the database.

I. Create a student record in the database.

Step 17. Create a student controller. Inside the controller's folder, create a studentController.js.

const student = require("../models/studentModel");

Step 18. Import the student model in studentController.js as Student.

const Student = require("../models/studentModel");

//Create Student
const createStudent = async (req, res) => {
  try {
    const _student = await Student.create(req.body);
    res.status(200).json(_student);
  } catch (error) {
    console.log(error.message);
    res.status(500).json({ message: error.message });
  }
};

module.exports = {
  createStudent,
};

Create a variable for Student.create a response as _student.

    const _student = await Student.create(req.body);
    res.status(200).json(_student);

Student. create(req.body) Student is Model, It is return status (200) success and _student Details.

createStudent is a module. It will be an export for access.

module.exports = {
  createStudent,
};

Create a route

Step 19. Create a Student Route. Inside the routes folder, create a studentRoute.js.

const express = require("express");
const router = express.Router();
const {createStudent}= require("../controllers/studentController");

//Create Student
router.post("/student", createStudent);
module.exports = router;
  1.  Import the express and use the Router as the router.
  2. Import the student controller with the module.
    const express = require("express");
    const router = express.Router();
    const {createStudent}= require("../controllers/studentController");

     

  3. Create the route it is post method = router.post("/student", createStudent);
  4. Router module exports.
    //Create Student
    router.post("/student", createStudent);
    module.exports = router;

Step 20. Import the router to the index page.

Go to the index page, import the router, and set the route.


const studentRoute = require("./routes/studentRoute");
app.use(express.json());

//Student Route
app.use("/api", studentRoute);
  1. Import the studentRoute is required from studentRoute.
  2. Read the JSON format from the request we access express.json().
  3. Set studentRoute using express. app.use("/api", studentRoute);
    require("dotenv").config();
    const express = require("express");
    const mongoose = require("mongoose");
    const app = express();
    const MONGO_CONNECTION = process.env.MONGO_CONNECTION;
    
    const studentRoute = require("./routes/studentRoute");
    app.use(express.json());
    
    //Student Route
    app.use("/api", studentRoute);
    
    mongoose
      .connect(MONGO_CONNECTION)
      .then(() => {
        console.log("connected to MongoDB Atlas");
        app.listen(3000, () => {
          console.log(`Node API app is running on port 3000`);
        });
      })
      .catch((error) => {
        console.log(error);
      });
    

Go to the postman and check if the API call works or not. using this route  http://localhost:3000/api/student.

Create Operation

Picture 16. Enter the sample student data and send it. It is a post method and gets the response as well.

We can check whether the data was added or not in the database.

Node Student

Picture 17. Here, we can see the database and Postman response data both are the same.

II . Read all student records in the database.

Step 21.  Go to the studentController.js and add this code.

const _students = await Student.find({});  In the MVC pattern, we get the data from the model. Student. find({}) . It Sends the results in the object, It is an HTTP GET method.

//Get All Students
const getAllStudents = async(req, res)=>{
  try {
    const _students = await Student.find({});
    res.status(200).json(_students);
  } catch (error) {
     res.status(500).json({ message: error.message });
  }
}

Here we created the getAllStudents module and exported the module also. module.exports = { createStudent, getAllStudents,};

Step 22.  Go to the studentRoute and import the getAllStudents module.

const { createStudent, getAllStudents,} =require("../controllers/studentController");
//Get All Students
router.get("/student", getAllStudents);

Model. Find is HTTP GET method. router.get("/student", getAllStudents);

Check the postman here. GET method and using this route. http://localhost:3000/api/student.

Fetch Student

Picture 18: Here, we can see the get all student results.

III . Read a student record in the database.

Step 23.  Go to the studentController.js and add this code. 

When getting a single record, use the findById method and pass the ID to the params.

//Get the Student
const getStudent = async(req, res)=>{
  try {
    const {id} = req.params;
    const _student = await Student.findById(id);
    res.status(200).json(_student);
  } catch (error) {
     res.status(500).json({ message: error.message });
  }
}
module.exports = {
  createStudent,
  getAllStudents,
  getStudent,
};
  1. Get the id from req.params, and pass the id to findById(id);  and also export the getStudent module.
  2. Go to the studentRoute and import the getStudent module. It is also the HTTP GET method. 
  3. Check the postman here. GET method and use this route with Id. http://localhost:3000/api/student/{id}.

GET

Picture 19. Here we can see a single record by id.

IV . Update a student record in the database.

Step 24.  Add this code in studentController.js.

const updateStudent = async (req, res) => {
  try {
    const { id } = req.params;
    const _student = await Student.findByIdAndUpdate(id, req.body);
    // we cannot find any Student in database
    if (!_student) {
      return res
        .status(404)
        .json({ message: `cannot find any student with ID ${id}` });
    }
    const updatedStudent = await Student.findById(id);
    res.status(200).json(updatedStudent);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};

When we update the student record, First, we find the student ID and will update the student details.

const _student = await Student.findByIdAndUpdate(id, req.body);   findByIdAndUpdate(id, req.body) There are two type parameters: id is a student ID, and req.body is an update detail.

Find the ID from the student table, If data is there, we can update student details if data is not found, return status 404 and message.

  if (!_student) {
      return res
        .status(404)
        .json({ message: `cannot find any student with ID ${id}` });
    }
  1. Export the updateStudent module. And go to the studentRoute and import the updateStudent module. It is the HTTP PUT method. 
  2. Check the postman here. PUT method and use this route with Id and req.body. http://localhost:3000/api/student/{id}

PUT

Picture 20: Here, we can see the updated record by ID with the request body.

Node_studentAPI

Picture 21. Here, we can see the updated record from the database.

IV . Delete a student record in the database.

Step 25. Add this code in studentController.js.

//Delete a Student
const deleteStudent = async (req, res) => {
  try {
    const { id } = req.params;
    const _student = await Student.findByIdAndDelete(id);
    if (!_student) {
      return res
        .status(404)
        .json({ message: `cannot find any student with ID ${id}` });
    }
    res.status(200).json(_student);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};

Here also find the data by ID and delete the record. We use the Student.findByIdAndDelete(id) method,  this method finds the data by ID; if data is there, then data will be deleted. 

 const _student = await Student.findByIdAndDelete(id);  ID will be passed from request params.   const { id } = req.params;

But data is not found and returns the error status 404 and error message.

 if (!_student) {
      return res
        .status(404)
        .json({ message: `cannot find any student with ID ${id}` });
    }

If delete the record res.status(200).json(_student); return the response deleted data.

  1. Export the deleteStudent module. And go to the studentRoute and import the deleteStudent module. It is the HTTP DELETE method. 
  2. Check the postman here. DELETE method and use this route with Id and req.body. http://localhost:3000/api/student/{id}

Delete

Picture 22. Here we can see the deleted data.

DELETE

 

Picture 23. Check the data by id, but data is not found and returns the error status 404 and error message.

Summary

This article is advanced compared to my previous article. I explained What is MVC. How to apply the MVC architecture in a Node JS project and how to perform CRUD operations using Node Js, Express, Postman, and MongoDB. In this article, Perform CRUD operations API checking with Postman. I hope this article helps those Who have an interest in self-learning. To Keep in touch with me. Next article, I’m going to start a new subject, REACT js.


Similar Articles
Adelanka (PVT) LTD
Globally based Software Developing & Data Processing Company