Crud Operation using Node.js Express MongoDB

Crud Operation using Node.js Express MongoDB

In this post we have learn how to create crud operation using node.js express mongoDB. We have create crud operation using mongoose and node.js. Also we solve all about the related questions like crud using node.js and mongodb, crud operation with node.js and mongodb, crud using nodejs and mongodb, node js crud operation with mongodb example ect.

CRUD stands for Create, Read, Update and Delete. we have simple way to create crud operation in node.js using mongoose.

Crud Operation using Node.js Express MongoDB

Step 1 : Install MongoDB

First you can install mongoDB environment  on your system. Install mongoDB from official website https://www.mongodb.com.

step 2: Install required packages

Following package to you can easy to mongoose insert document in your project.

  • Express – popular web framework;
  • body-parser – body parser middleware, allows to access req.body property;
  • mongoose – Mongoose provides a straight-forward;

Following command to install express module in node js, install bosy-parser .

npm init -y
npm i express body-parser mongodb

Node.js crud operation with mongodb 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.

Read Also :  NodeJs Insert Data using Mongoose Save Function

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.

views/layout/layout.hbs

<!DOCTYPE html>
<html>
<head>
    <title>how to create crud operation with node.js and mongodb</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.

Read Also :  Update Data in MongoDB using Node js

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 getting data from mongodb using mongoose, get data from mongoose node js, how to get data from mongodb using mongoose.

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

router.get('/delete/:id', (req, res) => {
    Users.findByIdAndRemove(req.params.id, (err, doc) => {
        if (!err) {
            res.redirect('/list');
        }
        else { console.log('Error in user delete :' + err); }
    });
});

module.exports = router;

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

npm server.js