How to Update MongoDB Data Using Mongoose and Node.js Expresss

Update MongoDB Data Using Mongoose: In this tutorial, you will learn to update  MongoDB data with a great example. This example will give you the best concept to update other bulk data from the table. Even you will get a free script to integrate into the project.

This tutorial is shared with the Express MVC pattern. This means all the script is written with a separate Model, View & controller file that will be very simple to understand. So, You will easily learn How to Update  MongoDB data Using Mongoose Node.js Express.

update mongodb data using mongoose

 

Update  MongoDB Data Using Mongoose

Mongoose query is the best solution to Update MongoDB data. So, You should use it for writing the fetching query.

Before getting started, you will have to configure the following required things to execute Node.js Express on your computer.

Now, I’m going to explain this tutorial through the following steps:-

Basic Configuration

First of all, You must configure the following things:-

  •  Install Node.js or Express Application. You can learn it through the following URL

How to Install Express Application

  • After Installing Express Application, Create MVC Pattern as the following structure.
myapp/
  |__bin/
  |__config/
  |     |__database.js
  |__controllers/
  |     |__user-controller.js
  |__models/
  |     |__user-models.js
  |__node_modules/
  |__public/
  |__routes/
  |     |__user-route.js
  |__views/
  |     |__edit-user-form.ejs
  |     |__user-data-list.ejs
  |     |__user-form.ejs    
  |__package-lock.json
  |__package.json

 

  • You must connect MongoDB to Node.js using mongoose. you can learn it through the following URL.

Connect MongoDB with Node.js Using Mongoose

You can use the following mongoose script in Express to connect MongoDB to Node.js

File Path: config/database.php

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('disconnected',function(){
    console.log('database is disconnected successfully');
})

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

module.exports = conn;
  • First, You should Insert & Fetch MongoDB Data. If you don’t know, you can learn  through the following URL

 Insert Data Into MongoDB Using Mongoose and Express

 Fetch Data From MongoDB Using Mongoose and Express

Model – Write Mongoose Query to Update MongoDB Data

Now, do the following things to create a model for fetching  data from MongoDB

Load the mongoose module

var mongoose=require('mongoose');

Load the database module

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

Create a schema with the same name as input fields name

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

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

Write the following script to edit MongoDB data.

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

Write the following script to execute the Update query.

updateData:function(inputData, editId, callback){
                  
      userData= userTable.findByIdAndUpdate(editId, inputData);
      userData.exec(function(err, data){
        if (err) throw err;
         return callback(data);
      })}

 

Complete Script

File path: models/user-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={

     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);
      })
   }
   
}
    

 

Controller – Load Model to execute Update Query

Load the following  user-model.js in the controller

var userModel= require('../models/user-model');

Write the following script to  execute Edit Query

editData:function(req, res){
      var editId= req.params.id;
      userModel.editData(editId,function(data){
        res.render('edit-user-form',{userData:data});
      })
}

Write the following script to  execute Update Query

updateData:function(req, res){
      var inputData= req.body;
      var editId= req.params.id;
      userModel.updateData(inputData, editId,function(data){
         res.redirect('/user/data-list')
         console.log(data.affectedRows + " record was updated");
      });
}

 

Complete Script:

File Path: controllers/user-controller.js

var userModel= require('../models/user-model');
module.exports={
  
    editData:function(req, res){
      var editId= req.params.id;
      userModel.editData(editId,function(data){
        res.render('edit-user-form',{userData:data});
      })
    },
    updateData:function(req, res){
      var inputData= req.body;
      var editId= req.params.id;
      userModel.updateData(inputData, editId,function(data){
         res.redirect('/user/data-list')
         console.log(data.affectedRows + " record was updated");
      });
    }

}

View – Write HTML Code to Create Edit Form

Write the following code to create an HTML Form & display Edit data.

<form action="/user/edit/<%=userData.id %>" 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>

Use the following CSS code to design the HTML Table

* {
  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;
  }

Complete HTML & CSS Code

File Path: views/edit-user-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="/user/edit/<%=userData.id %>" 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>
        </div>
</div>
<!--====form section start====-->



</body>
</html>

Route – Create & Load Route to Update Data

Create Route:

Load  user-controller.js  using the following script

var userController= require('../controllers/user-controller');

Create the following route to edit data

router.get('/edit/:id',userController.editData);

Create the following route to update data

router.post('/edit/:id',userController.updateData);

 

Complete route script:

File Path: routes/user-route

var express = require('express');
var router = express.Router();
var userController= require('../controllers/user-controller');

router.get('/edit/:id',userController.editData);
router.post('/edit/:id',userController.updateData);

module.exports = router;

Load Route:

load user-route.js in the app.js

var userRouter = require('./routes/user-route');
app.use('/user', userRouter);

Suggestion:

Dear developers, I hope you have understood the above script, Now you are able to Update  MongoDB Data using Mongoose and Node.js express

I will share more tutorials on Node.js/Express asap. So, Continue to visit this website.

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

Leave a Comment