Update Data in MongoDB using Node js

Update Data in MongoDB using Node js

In this post we have learn how to update data in MongoDB using Node js. I explained simply about how to node js mongodb update by _id example. In this article, we will implement a mongodb update document.

In this article we will solve all questions like update in mongodb using node js, how to update data in mongodb using node js, update document in mongodb using node js, update data in mongodb node js, how to update record in mongodb using node js ect.

Update Data in MongoDB using Node js Example

Step 1 : Create the db.js file on your root directory in this file we will import mongoose module and connect with mongoDB database. In this file you include your model.

db.js

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/testdb', { useNewUrlParser: true }, (err) => {
    if (!err) {
        console.log('MongoDB Connection Succeeded.')
    }else {
        console.log('Error in DB connection : ' + err)
    }
});

require('./models/users');

Step 2 :  Create views/layout/layout.hbs file. If you have use handlebars(.hbs) extension, hbs require views folder.

Read Also :  Crud Operation using Node.js Express MongoDB

views/layout/layout.hbs

<!DOCTYPE html>
<html>
<head>
    <title>how to update data in mongodb using node js</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO"
        crossorigin="anonymous">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body class="bg-info">
    <div class="row">
        <div class="col-md-6 offset-md-3" style="background-color: #fff;margin-top: 25px;padding:20px;">
            {{{body}}}
        </div>
    </div>
</body>
</html>

Step 3 : Create the views/user/list.hbs file. In this file we have create basic html form for get data from mongoose nodejs. In this form we have display user data using mongoose and nodejs.

views/user/list.hbs

<h3><a class="btn btn-secondary" href="/"><i class="fa fa-plus"></i> Create New</a> User List</h3>
<table class="table table-striped">

    <thead>
        <tr>
            <th>Username</th>
            <th>Email</th>
            <th>Passwod</th>
            <th></th>
        </tr>
    </thead>

    <tbody>
        {{#each list}}
        <tr>
            <td>{{this.username}}</td>
            <td>{{this.email}}</td>
            <td>{{this.password}}</td>
            <td>
                <a href="/{{this._id}}"><i class="fa fa-pencil fa-lg" aria-hidden="true"></i></a>
                <a href="/delete/{{this._id}}" onclick="return confirm('Are you sure to delete this record ?');"><i class="fa fa-trash fa-lg" aria-hidden="true"></i></a>
            </td>
        </tr>
        {{/each}}
    </tbody>
</table>

Step 4 : Create the server.js file in root directory. This file is by default run your project. In this file we have include db.js connection file.

server.js

require("./db");
const path = require("path");
const express = require("express");
const bodyparser = require("body-parser");
const exphbs = require("express-handlebars");
const userController = require("./controllers/userController");

var app = express();
app.use(bodyparser.urlencoded({
    extended: true
}));

app.use(bodyparser.json());
app.set('views', path.join(__dirname, '/views/'));
app.engine('hbs', exphbs({ extname: 'hbs', defaultLayout: 'layout',
        runtimeOptions: {
          allowProtoPropertiesByDefault: true,
          allowProtoMethodsByDefault: true,
        },
     layoutsDir: __dirname + '/views/layout' }));

app.set('view engine', 'hbs');
app.listen(3000, () => {
    console.log('Express server started at port : 3000');
});

app.use('/', userController);

Step 5 : Create controllers/userController.js file. In file we have create router and write some code like how to insert data in mongodb using node js, update data in MongoDB using Node js, update data in mongodb node js.

Read Also :  Fetch Data from Mongodb using Mongoose, Express.js, Node.js

controllers/userController.js

const express = require("express");
var router = express.Router();
const mongoose = require('mongoose');
const Users = mongoose.model('Users');
mongoose.set('useFindAndModify', false);

router.get("/", (req,res) =>{
    res.render("user/addOrEdit",{
        titleName : 'Insert User'
    });
});

router.post("/", (req,res) =>{
    if(req.body._id == "")
        insertRecord(req,res);
    else
        updateRecord(req,res);
});

function insertRecord(req,res){
    var users = new Users();
    users.username = req.body.username;
    users.email = req.body.email;
    users.password = req.body.password;
    users.save((err,doc) =>{
        if(!err)
        res.redirect("list");
        else{
            if (err.name == 'ValidationError') {
                handleValidationError(err, req.body);
                res.render("user/addOrEdit", {
                    titleName: "Insert User",
                    users: req.body
                });
            }
        }
    });
}

function updateRecord(req,res){
    Users.findByIdAndUpdate({ _id: req.body._id }, req.body, { new: true }, (err, doc) => {
        if (!err) { res.redirect('/list'); }
        else {
            if (err.name == 'ValidationError') {
                handleValidationError(err, req.body);
                res.render("user/addOrEdit", {
                    viewTitle: 'Update User',
                    users: req.body
                });
            }
            else
                console.log('Error during record update : ' + err);
        }
    });
}

router.get('/list', (req, res) => {
    Users.find((err, docs) => {
        if (!err) {
            res.render("user/list", {
                list: docs
            });
        }
        else {
            console.log('Error in retrieving users list :' + err);
        }
    });
});

function handleValidationError(err, body) {
    for (field in err.errors) {
        switch (err.errors[field].path) {
            case 'username':
                body['usernameError'] = err.errors[field].message;
                break;
            case 'email':
                body['emailError'] = err.errors[field].message;
                break;
            case 'password':
                body['passwordError'] = err.errors[field].message;
                    break;
            default:
                break;
        }
    }
}

router.get('/:id', (req, res) => {
    Users.findById(req.params.id, (err, doc) => {
        if (!err) {
            res.render("user/addOrEdit", {
                titleName: "Update User",
                users: doc
            });
        }
    });
});

module.exports = router;

Step 6 : Complete all steps after you can enter the following command.

npm server.js

 

Read Also :  NodeJs Insert Data using Mongoose Save Function