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.

 

MongoDB CRUD Operations in Node.js Express

Before Getting Started 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/
  |__bin/
  |__config/
  |     |__database.js
  |__controllers/
  |     |__crud-controller.js
  |__models/
  |     |__crud-models.js
  |__node_modules/
  |__public/
  |__routes/
  |     |__crud-route.js
  |__views/
  |     |__crud-form.ejs
  |     |__crud-list.ejs
  |__package-lock.json
  |__package.json

CRUD Basic Configuration

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

Create Model, View, Controller

Create Some files in the Model, View, & Controller as the following ways

Create controllers & models  in myapp Express Folder.

Model 

  • Create  crud-model.js file in the models  folder
  • Load it in the crud-controller.js by using var crudModel=require('../models/crud-model');

File Path: models/crud-model.js

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

module.exports={
// CRUD model script will be defined here
}

 Controller 

  • Create file crud-controller.js in the controllers  folder
  • Load it in the crud-route.js by using var crudController=require('../controllers/crud-controller.js');

File Path: controllers/crud-controller.js

var crudModel=require('../models/crud-model');
module.exports={

     CRUD controller script will be defined here
}

View folder

Create the following files in  the views  folder

  • Create file crud-form.ejs to create HTML Form
  •  Create  crud-list.ejs to create HTML Table

Connect Node.js to MongoDB

  • Create config folder in the myapp express folder
  • Create database.js file in the config folder
  • 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('../config/database.js');

Write the following script to connect Node.js with MongoDB

File Path: config/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 Schema Using Mongoose

Write the following mongoose script in crud-model.js  to create a schema

File Name: crud-model.js

var mongoose=require('mongoose');

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

userTable=mongoose.model('users',userSchema);

 

MongoDB CRUD Operations

In MongoDB CRUD Operation, you will learn to create, Read, & delete MongoDB data in Node.js Express using Mongoose. So, configure the following steps.

 Create MongoDB Data

In the case of Create, You can insert user data through the HTML form into the MongoDB Collection.

Create Script is written in the following  Model, View,& Controller folders. So, User Input data can be created easily into the MongoDB collection.

 Write a create query in Model 

Write the  Create query using mongoose in  crud-model.js

createData:function(inputData, callback){
                 
       userData= new userTable(inputData);
       userData.save(function(err, data){
         if (err) throw err;
          return callback(data);
       })

    },

Create an HTML Form in View

Write HTML code to create a form  in the file crud-form.js

<form action="/crud/create" method="POST">
          <label>Full Name</label>
          <input type="text" placeholder="Enter Full Name" name="fullName" required >
          <label>Email Address</label>
          <input type="email" placeholder="Enter Email Address" name="emailAddress" required>
          <label>City</label>
          <input type="city" placeholder="Enter Full City" name="city" required>
          <label>Country</label>
          <input type="text" placeholder="Enter Full Country" name="country" required>
          <button type="submit">Submit</button>
    </form>

Write Script  in Controller to run Create Query

Write the following Create script in the file crud-controller.js

  • This script will display the crud-form.ejs on the browser.
userForm:function(req,res){
        res.render('crud-form')
   },

 

  • This script will call the crud-model.js and insert user input into the crud  table.
createData:function(req, res){
        var inputData= req.body;
        crudModel.createData(inputData, function(data){
           res.render('crud-form')
           console.log(" record was created");
        });
   },

 Read MongoDB Data

In the case of Read, You can fetch user data in the HTML table from the MongoDB Collection.

Read Script is written in the following  Model, View,& Controller folder. So, Data of MongoDB collection will be Fetched easily.

Write Read Query in Model 

Write the following Read query in the file crud-model.js

fetchData:function(callback){
       var userData=userTable.find({});
       userData.exec(function(err, data){
           if(err) throw err;
           return callback(data);
       })
       
    },

Write Script in Controller to run Read Query

Write the following Read script in the file crud-controller.js

fetchData:function(req, res){
      
      crudModel.fetchData(function(data){
          res.render('crud-list',{userData:data});
      })
    },

Create HTML Table and Fetch data  in View

Write the  following script in the file crud-list.ejs and Fetch data from MongoDB collection

<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>

 Update MongoDB Data

In the case of Update, You can update  data of MongoDB Collection through the HTML form

Update Script is written in the following  Model, View,& Controller  Folder. So, User MongoDB data will be Updated easily.

Write Update Query in Model 

Write the following Update query in the file crud-controller.js

  • This Query will fetch the Input data in the crud-form from the  users table &   edit it on the basis of id
editData:function(editId,callback){
        var userData= userTable.findById(editId);
        userData.exec(function(err, data){
         if(err) throw err;
         return callback(data);
      })
     },

 

  • This Query will update the Input data of   users table
updateData:function(inputData, editId, callback){
                  
      userData= userTable.findByIdAndUpdate(editId, inputData);
      userData.exec(function(err, data){
        if (err) throw err;
         return callback(data);
      })
   },

Write Script in Controller to Run Update Query

Write the following Update script in the file crud-controoler.js

  • This script will edit the table record
editData:function(req, res){
      var editId= req.params.id;
      crudModel.editData(editId,function(data){
        res.render('crud-form',{userData:data});
      })
    },
  • This script will update the table record
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");
  });
},

Update Table Data  From View

Write the following in the file crud-form.js

<form action="<%=(typeof userData!='undefined')? '/crud/edit/'+userData.id:'crud/create'%>" method="POST">
          <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>

 

Delete MongoDB Data

In the case of Delete, You can delete  data of MongoDB collection from the HTML table

Delete Script is written in the following  Model, View,& Controller folder. So, MongoDB data will be Deleted easily.

Write Delete Query in Model 

Write the following Delete query in the file crud-model.js

deleteData:function(deleteId, callback){
                  
      userData= userTable.findByIdAndDelete(deleteId);
      userData.exec(function(err, data){
        if (err) throw err;
         return callback(data);
      })
   }

 

Delete MongoDB data From View

You can delete data from the HTML table of  crud-list.ejs

Write  Script in Controller to Run Delete Query

Write the following  script in the file crud-controoler.js

deleteData:function(req, res){
      
      var deleteId= req.params.id;
      crudModel.deleteData(deleteId,function(data){
         res.redirect('/crud/data-list')
         console.log(" record was deleted");
      });
    }

 

MongoDB CRUD Routing

Now, you will need to create crud route to execute the CRUD Operation. So, config the following steps.

You can read official Express Routing Documentation to know more about it.

Create CRUD Route

Create file crud-route.js in the routes  folder.

File Path: routes/crud-route

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;

Load CRUD Route

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

 

Complete CRUD Script

Now, you can use the following script directly in your Node.js application.

File Path: models/crud-model.js

Copy & paste the following script in the crud-model.js

var mongoose=require('mongoose');
var db = require('../config/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);
      })
   }
}
    

 

File Path: controllers/crud-controller.js

Copy & paste the following script in the crud-controller.js

var crudModel= require('../models/user-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");
      });
    }

}

 

File Path: views/crud-form.ejs

Copy & paste the following script in the 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>

 

 

File Path: views/crud-list.js

Copy & paste the following script in the 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>

 

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

    Reply
    • 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

      Reply

Leave a Comment