MongoDB CRUD Operations Using Node.js Express and Mongoose

MongoDB CRUD Operations: In this tutorial, You will get the best way to create CRUD  Operation Using Mongoose. Even It is explained with a simple example that makes it easy to learn & understand.

In the case of CRUD, You can CREATE, READ, UPDATE and DELETE data. you will learn these operations in detail with MongoDB Database. And these operations had been made very simple & easy by creating with Express MVC Pattern.

Express MVC pattern means that the CRUD operations are created in Model,  View & controller separately. Therefore you will get the logic script in the controller, database query in Model, form & data list page in view.

mongodb crud operations

These operations are given step by step with simple & speaking language. So, you need not worry about it. just read the complete tutorial. you will easily learn the MongoDB CRUD Operations Using Node.js Express and Mongoose.

 

How to Create MongoDB CRUD Operations in Node.js Express

Before Getting Started with this Script, You must do the following things.

  •  Install Node.js or Express Application. Know more about it through the following URL

How to Install Express Application

  • After Installing Express Application, Create Express MVC Pattern like the following structure
myapp/
  |__controllers/
  |     |__crud-controller.js
  |__models/
  |     |__crud-models.js
  |__routes/
  |     |__crud-route.js
  |__views/
  |     |__crud-form.ejs
  |     |__crud-list.ejs
  |__database.js

Now, you need to create  MVC, MongoDB &  collection to implement CRUD Operation in Node.js Express. So, configure the following steps

Connect Node.js to MongoDB

  • Create database.js file
  • Use the following script in the database.js file to connect Node.js express to MySQL Database.
  • Load database.js in the crud-model.js by using  var db=require('../database.js');

Write the following script to connect Node.js with MongoDB

File Name – database.js

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/test', {useNewUrlParser: true});

var conn = mongoose.connection;

conn.on('connected', function() {
    console.log('database is connected successfully');
});

conn.on('error', console.error.bind(console, 'connection error:'));

module.exports = conn;

 

To know more about MongoDB database connection, Open the following URL

Connect Node.js with MongoDB Using Mongoose

Create an HTML Form to Enter Data

You need to create an HTML table to enter data and submit and update  MongoDB data. So, use code from the following File

File Name – crud-form.ejs

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
* {
  box-sizing: border-box;}
.user-detail {
    height: 100vh;
    border: 2px solid #f1f1f1;
    padding: 16px;
    background-color: white;
    width: 30%;}
input{
  width: 100%;
  padding: 15px;
  margin: 5px 0 22px 0;
  display: inline-block;
  border: none;
  background: #f1f1f1;}
input[type=text]:focus, input[type=password]:focus {
    background-color: #ddd;
    outline: none;}
button[type=submit] {
    background-color: #434140;
    color: #ffffff;
    padding: 10px 20px;
    margin: 8px 0;
    border: none;
    cursor: pointer;
    width: 100%;
    opacity: 0.9;
    font-size: 20px;}
label{
  font-size: 18px;;}
button[type=submit]:hover {
  background-color:#3d3c3c;}
  .form-title a, .form-title h2{
   display: inline-block;
   
  }
  .form-title a{
      text-decoration: none;
      font-size: 20px;
      background-color: green;
      color: honeydew;
      padding: 2px 10px;
  }
 
</style>
</head>
<body>
<!--====form section start====-->
<div class="user-detail">
    <div class="form-title">
    <h2>CRUD Form</h2>
    <a href="/user/data-list">CRUD List</a>
    
    </div>
    <hr>
    <form action="<%=(typeof userData!='undefined')? '/crud/edit/'+userData.id:'crud/create'%>">
          <label>Full Name</label>
          <input type="text" placeholder="Enter Full Name" name="fullName" required value="<%=(typeof userData!='undefined')? userData.fullName:''%>">
          <label>Email Address</label>
          <input type="email" placeholder="Enter Email Address" name="emailAddress" required value="<%=(typeof userData!='undefined')? userData.emailAddress:''%>">
          <label>City</label>
          <input type="city" placeholder="Enter Full City" name="city" required value="<%=(typeof userData!='undefined')? userData.city:''%>">
          <label>Country</label>
          <input type="text" placeholder="Enter Full Country" name="country" required value="<%=(typeof userData!='undefined')? userData.country:''%>">
          <button type="submit">Submit</button>
    </form>
        </div>
</div>
<!--====form section start====-->



</body>
</html>

 

Create a CRUD Model

To create a crud model, you have to implement the following steps in crud-model.js

  •  Include the mongoose module and database connection file database.js
  • Create a mongoose schema for fullName, emailAddress, city & country and assign it to userSchema
  • Pass a table named ‘user’  and userSchema to the model method.
  • Create a module.exports{} and define the following methods.
    • CreateData – It runs to insert data into the database.
    • fetchData – It runs to fetch data from the database.
    • editData – It runs to edit data based on the id.
    • updateData – It runs to update data.
    • deleteData – It runs to delete data.

File Name – crud-model

var mongoose=require('mongoose');
var db = require('../database');

// create an schema
var userSchema = new mongoose.Schema({
            fullName: String,
            emailAddress:String,
            city:String,
            country:String
        });

userTable=mongoose.model('users',userSchema);
        
module.exports={
     createData:function(inputData, callback){
                  
        userData= new userTable(inputData);
        userData.save(function(err, data){
          if (err) throw err;
           return callback(data);
        })

     },
     fetchData:function(callback){
        var userData=userTable.find({});
        userData.exec(function(err, data){
            if(err) throw err;
            return callback(data);
        })
        
     },
     editData:function(editId,callback){
        var userData= userTable.findById(editId);
        userData.exec(function(err, data){
         if(err) throw err;
         return callback(data);
      })
     },
     updateData:function(inputData, editId, callback){
                  
      userData= userTable.findByIdAndUpdate(editId, inputData);
      userData.exec(function(err, data){
        if (err) throw err;
         return callback(data);
      })
   },
   deleteData:function(deleteId, callback){
                  
      userData= userTable.findByIdAndDelete(deleteId);
      userData.exec(function(err, data){
        if (err) throw err;
         return callback(data);
      })
   }
}

 

Create a CRUD Controller

To create a CRUD controller, you will have to implement the following steps –

First of all, include the crud-model.js

  • Create module.exports{} object and define the following method
    • userForm – It can display the crud form in the browser
    • createData – It calls a method CreateData form the crud model on the submit the input values from the HTML form.
    • fetchData – It calls a method fetchData form the crud model to display data in the HTML table
    • editData – It calls a method editData form the crud model on click the edit button in HTML table
    • updateData  – It calls a method updateData form the crud model on the submit updated values from the HTML form
    • deleteData – It calls a method deleteData form the crud model on click the delete button in HTML table

File Name – crud-controller.js

var crudModel= require('../models/crud-model');
module.exports={
    userForm:function(req,res){
         res.render('crud-form')
    },
    createData:function(req, res){
         var inputData= req.body;
         crudModel.createData(inputData, function(data){
            res.render('crud-form')
            console.log(" record was created");
         });
    },
    fetchData:function(req, res){
      
      crudModel.fetchData(function(data){
          res.render('crud-list',{userData:data});
      })
    },
    editData:function(req, res){
      var editId= req.params.id;
      crudModel.editData(editId,function(data){
        res.render('crud-form',{userData:data});
      })
    },
    updateData:function(req, res){
      var inputData= req.body;
      var editId= req.params.id;
      crudModel.updateData(inputData, editId,function(data){
         res.redirect('/crud/data-list')
         console.log(" record was updated");
      });
    },
    deleteData:function(req, res){
      
      var deleteId= req.params.id;
      crudModel.deleteData(deleteId,function(data){
         res.redirect('/crud/data-list')
         console.log(" record was deleted");
      });
    }

}

 

Create an HTML Table to Display Data

You have to display data in the HTML table that. So, use the given script from the following file.

File Name – crud-list.ejs

<!DOCTYPE html>
<html lang="en">
<head>
  <title></title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>
    * {
  box-sizing: border-box;}
.user-detail {
    height: 100vh;
    border: 2px solid #f1f1f1;
    padding: 16px;
    background-color: white;
    width: 30%;}
input{
  width: 100%;
  padding: 15px;
  margin: 5px 0 22px 0;
  display: inline-block;
  border: none;
  background: #f1f1f1;}
input[type=text]:focus, input[type=password]:focus {
    background-color: #ddd;
    outline: none;}
button[type=submit] {
    background-color: #434140;
    color: #ffffff;
    padding: 10px 20px;
    margin: 8px 0;
    border: none;
    cursor: pointer;
    width: 100%;
    opacity: 0.9;
    font-size: 20px;}
label{
  font-size: 18px;;}
button[type=submit]:hover {
  background-color:#3d3c3c;}
  .form-title a, .form-title h2{
   display: inline-block;
   
  }
  .form-title a{
      text-decoration: none;
      font-size: 20px;
      background-color: green;
      color: honeydew;
      padding: 2px 10px;
  }
    table, td, th {  
      border: 1px solid #ddd;
      text-align: left;
    }
    
    table {
      border-collapse: collapse;
      width: 50%;
     

    }
    .table-data{
        position: relative;
      left:50px;
      top:50px;
    }
    th, td {
      padding: 15px;
    }
body{
    overflow-x: hidden;
}
.list-title a, .list-title h2{
   display: inline-block;
   margin: 0px 35px;
  }
  .list-title a{
      text-decoration: none;
      font-size: 20px;
      background-color: green;
      color: honeydew;
      padding: 2px 10px;
  }
    </style>
</head>
<body>

<!--====form section start====-->
    <div class="table-data">
        <div class="list-title">
 <h2>CRUD List</h2>
            <a href="/user">CRUD From</a>
            </div>
<br><br>
    <table border="1" >
        <tr>
            <th>S.N</th>
            <th>Full Name</th>
            <th>Email Address</th>
            <th>City</th>
            <th>Country</th>
            <th>Edit</th>
            <th>Delete</th>
        </tr>
        
        <%
        if(userData.length!=0){
        var i=1;
        userData.forEach(function(data){
        %>
        <tr>
            <td><%=i; %></td>
            <td><%=data.fullName %></td>
            <td><%=data.emailAddress %></td>
            <td><%=data.city %></td>
            <td><%=data.country %></td>
            <td><a href="/crud/edit/<%=data.id%>">Edit</a></td>
            <td><a href="/crud/delete/<%=data.id%>">Delete</a></td>
        </tr>
        <%  i++; }) %>
        <% } else{ %>
            <tr>
                <td colspan="7">No Data Found</td>
            </tr>
        <% } %>
    </table>
    </div>
</body>
</html>

 

Create a CRUD Route

To create a CRUD route, configure the following steps –

  • Include express module & user-controller.js
  • Get a router method from the express module
  • Create the /crud-form and /edit/:id route with the post method
  • Also, create /data-list, /edit/:id and /delete/:id with the get method.
  • At last, export the router module

File Name – crud-route.js

var express = require('express');
var router = express.Router();
var userController= require('../controllers/user-controller');
/* GET users listing. */
router.get('/', userController.userForm);
router.post('/create',userController.createData);
router.get('/data-list',userController.fetchData);
router.get('/edit/:id',userController.editData);
router.post('/edit/:id',userController.updateData);
router.get('/delete/:id',userController.deleteData);
module.exports = router;

 

Include CRUD Route in app.js

You have to include & use the CRUD route in the root file app.js. If you forget it, your CRUD app will not work

File Name – app.js

var crudRouter = require('./routes/crud-route');

app.use('/crud', crudRouter);


Run CRUD Operation App

Now, You can run your CRUD app with the following URL.

First of all, Enter the following URL to display the CRUD Form in your browser.

http://localhost:3000/crud/crud-form

You can Enter the following URL in your web browser to display data in the HTML table

http://localhost:3000/crud/crud-list

When you submit the CRUD form with input values then the following URL will be called with the POST method to insert data into the database

http://localhost:3000/crud/create

When you click the edit button in the HTML table, then It will redirect to the following URL to display input values in the CRUD form based on the id.

http://localhost:3000/crud/edit/:id

When you submit the CRUD form after changing the existing values then It will redirect to the following URL to update the data. based on a particular id

http://localhost:3000/crud/edit/:id

When you click the delete button in the HTML table then It will redirect to the following URL to delete data from the tables.

http://localhost:3000/crud/delete/:id

Suggestion –

Dear developers, I hope you have understood the above script, Now you are able to develop MongoDB CRUD Operations using Node.js & Mongoose.

So, Continue to visit my site and share this tutorial with your friends who are searching for it. I will share more tutorials related to Node.js / Express as soon as possible.

If you have any doubts or questions. You can directly ask me through the below comment box.

 

2 thoughts on “MongoDB CRUD Operations Using Node.js Express and Mongoose”

  1. Thanks a ton for the good explanation. it helps a lot.

    I am getting the below error. Can you please guide me

    router.get(‘/list’,apiController.fetchData);
    ^

    TypeError: Cannot read property ‘fetchData’ of undefined

    • Hi Raj,
      you need to check fetchData is defined or not in the apicontroller file. if it is defined then check its spelling. This error will be definitely solved

Comments are closed.