Update MongoDB Data Using Mongoose and Node.js

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

 

How to Update MongoDB Data Using Mongoose and Node.js

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

Before getting started, you must

Insert data into MongoDB Table and Fetch Data From MongoDB table to display in the HTML table.

Install Express Application and create the following files & folders for creating an MVC pattern

myapp/
  |__controllers/
  |     |__update-controller.js
  |__models/
  |     |__update-models.js
  |__routes/
  |     |__update-route.js
  |__views/
  |     |__user-form.ejs    
  |__database.js
  |

connect MongoDB to Node.js using mongoose. So, you can use the code from the following file

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

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

module.exports = conn;

1. Create a Model to Update Data

Now, do the following things to create a model –

  • Include the mongoose module and the database connection file
  • Create a schema with the same name as the input fields name
  • Write the mongoose query to edit MongoDB data.
  • Write the  mongoose query to execute the Update data

File Name – update-model.js

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

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

 

2. Create a Controller to update data

Configure the following steps to create a controller –

  • Include a controller file update-controller.js
  • Write a script to call the function editData  and updateData from the model

File Name – update-controller.js

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

}

 

3. Create an edit link in the HTML Table

You have to create an HTML button with a delete link in the HTML table that code was created in the user-table.ejs. So. open this file and write the following line of code

<td><a href="/edit/<%=data.id%>">Edit</a></td>

3. Create an HTML Form to update data

Now, create a new HTML form otherwise you can use the existing form that is used to insert data. This form will be opened when you click the edit link in the HTML table. After that existing input values will be shown based on the particular id in that form.

File Name – 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>

 

4. Create a Route to delete data

To create a route, you will have to go through the following steps –

  • Include a controller file fetch-controller.js
  • Create the  route /edit/:id with the get method to edit data
  • Create the  route /edit/:id with the post method to update data
  • Export the Router module

File Name – update-route.js

var express = require('express');
var router = express.Router();
var updateController= require('../controllers/update-controller');

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

module.exports = router;

5. Include the Route in the app.js

You must include and use the created route in the main file app.js. If you forget it then your created router will not work.

File Name – app.js

var updateRouter = require('./routes/update-route');
app.use('/', updateRouter);

 

6. Run Node.js App to update MongoDB data

First of all, you have to enter the following URL in your browser to fetch data from the database and display data with the edit button link in the HTML table.

http://localhost:3000/fetch-data

When you click the edit button link that is shown in the HTML table then It will redirect through the post request to the following URL to update MongoDB data.

http://localhost:3000/edit/id

 

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

Categories Node.js

Leave a Comment