Node js Express MongoDB CRUD Example Tutorial

CRUD (Create, Read, Update, Delete) operations help us to manipulate data from the database, In this tutorial, you will learn how to create CRUD (Create, Read, Update, Delete) operations application in node js express js with MongoDB database using mongoose.

Node js Express + Mongodb + CRUD Operation Application With Mongoose Example

Here are steps:

Step 1 – Create Node Express js App

Run the following command on cmd to create node js app:

mkdir my-app
cd my-app
npm init -y

Step 2 – Install express flash Validator ejs body-parser mongoose Modules

Run the following command on the cmd to express flash ejs body-parser MySQL dependencies :

npm install -g express-generator
npx express --view=ejs

npm install

npm install express-flash --save
npm install express-session --save
npm install body-parser --save
npm install express-validator cors --save
npm install mongoose

Step 3 – Connect App to MongoDB

Create a database.js file in application root directory, and add the following code into it to connect your app to the Mongodb database:

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;

Step 4 – Create Model

Create Models directory, and in this directory create userModel.js file:

const mongoose = require("../database");
// create an schema
var userSchema = new mongoose.Schema({
            name: String,
            email:String
        });
var userModel=mongoose.model('users',userSchema);
module.exports = mongoose.model("Users", userModel);

Step 5 – Create Fetch Insert Update Delete Routes

Create fetch insert update, delete routes from MongoDB in node js; so visit routes directory and open users.js route file; Then add the following insert update, delete in node js MongoDB routes into it:

var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var userModel = require('../models/userModel');
/* GET home page. */
router.get('/', function(req, res, next) {
    userModel.find((err, docs) => {
        if (!err) {
            res.render("users", {
                data: docs
            });
        } else {
            console.log('Failed to retrieve the Users List: ' + err);
        }
    });
});
// SHOW ADD USER FORM
router.get('/add', function(req, res, next) {
    // render to views/user/add.ejs
    res.render('users/add', {
        title: 'Add New User',
        name: '',
        email: ''
    })
})
// ADD NEW USER POST ACTION
router.post('/add', function(req, res, next) {
    req.assert('name', 'Name is required').notEmpty() //Validate name
    req.assert('email', 'A valid email is required').isEmail() //Validate email
    var errors = req.validationErrors()
    if (!errors) { //No errors were found.  Passed Validation!
        var userDetails = new userModel({
            name: req.body.name,
            email: req.body.email,
        });
        userDetails.save((err, doc) => {
            if (!err)
                req.flash('success', 'User added successfully!');
            res.redirect('/users');
            else
                res.render('users/add', {
                    title: 'Add New User',
                    name: user.name,
                    email: user.email
                })
        });
    } else { //Display errors to user
        var error_msg = ''
        errors.forEach(function(error) {
            error_msg += error.msg + '<br>'
        })
        req.flash('error', error_msg)
        res.render('users/add', {
            title: 'Add New User',
            name: req.body.name,
            email: req.body.email
        })
    }
})
// SHOW EDIT USER FORM
router.get('/edit/(:id)', function(req, res, next) {
    userModel.findById(req.params.id, (err, doc) => {
        if (!err) {
            res.render("users/edit", {
                title: "Update User Details",
                data: doc
            });
        } else {
            req.flash('error', 'User not found with id = ' + req.params.id)
            res.redirect('/users')
        }
    });
})
// EDIT USER POST ACTION
router.post('/update/:id', function(req, res, next) {
    req.assert('name', 'Name is required').notEmpty() //Validate nam
    req.assert('email', 'A valid email is required').isEmail() //Validate email
    var errors = req.validationErrors()
    if (!errors) {
        var user = {
            name: req.sanitize('name').escape().trim(),
            email: req.sanitize('email').escape().trim()
        }
        userModel.findByIdAndUpdate(req.body.id, {
            name: req.body.name
        } {
            email: req.body.email
        }, function(err, data) {
            if (err) {
                req.flash('error', 'Something Goes to Wrong!');
                res.render('users');
            } else {
                req.flash('success', 'User has been updated successfully!');
                res.redirect('/users');
            }
        });
    } else { //Display errors to user
        var error_msg = ''
        errors.forEach(function(error) {
            error_msg += error.msg + '<br>'
        })
        req.flash('error', error_msg)
        /**
         * Using req.body.name
         * because req.param('name') is deprecated
         */
        res.render('users/edit', {
            title: 'Edit user',
            id: req.params.id,
            name: req.body.name,
            email: req.body.email
        })
    }
})
// DELETE USER
router.get('/delete/(:id)', function(req, res, next) {
    userModel.findByIdAndRemove(req.params.id, (err, doc) => {
        if (!err) {
            res.redirect('/users');
        } else {
            console.log('Failed to Delete user Details: ' + err);
        }
    });
})
module.exports = router;

Step 6 – Create CRUD Views

Go to views directory and create a directory named users, and then create some views in it:

  • index.ejs
  • add.ejs
  • edit.ejs

Edit views/users/index.ejs file, and add the following code in it:

<!DOCTYPE html>
<html>
<head>
    <title>Fetch and display data in html table from mongodb in node js express</title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
</head>
<body>
    <div> <a href="/" class="btn btn-primary ml-3">Home</a> </div>
    <!--   <% if (messages.error) { %>
  <p style="color:red"><%- messages.error %></p>
<% } %> -->
    <% if (messages.success) { %>
    <p class="alert alert-success mt-4">
        <%- messages.success %>
    </p>
    <% } %>
    <br>
    <table class="table">
        <thead>
            <tr>
                <th scope="col">#</th>
                <th scope="col">Name</th>
                <th scope="col">Email</th>
                <th width="200px">Action</th>
            </tr>
        </thead>
        <tbody>
            <% if(data.length){
  for(var i = 0; i< data.length; i++) {%>
            <tr>
                <th scope="row">
                    <%= (i+1) %>
                </th>
                <td>
                    <%= data[i].name%>
                </td>
                <td>
                    <%= data[i].email%>
                </td>
                <td> <a class="btn btn-success edit" href="../users/edit/<%= data[i]._id%>">Edit</a>
                    <a class="btn btn-danger delete" href="../users/delte/<%= data[i]._id%>">delete</a>
                </td>
            </tr>
            <% }

   }else{ %>
            <tr>
                <td colspan="3">No user</td>
            </tr>
            <% } %>
        </tbody>
    </table>
</body>
</html>

Edit views/users/add.ejs and add the following code to it:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Node.js insert Data from Html Form to Mongodb Database - Tutsmake.com</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
</head>
<body>
    <div class="container mt-4">
        <div class="card">
            <div class="card-body">
                <% if (messages.success) { %>
                <p class="alert alert-success m2-4 mb-2"><%- messages.success %></p>
                <% } %>
                <form action="users/add" method="POST">
                    <div class="form-group">
                        <label for="firstName">Name</label>
                        <input type="text" class="form-control col-lg-9" id="name" aria-describedby="emailHelp" placeholder="Enter first name" name="name">
                    </div>
                    <div class="form-group">
                        <label for="exampleInputEmail1">Email address</label>
                        <input type="email" class="form-control col-lg-9" id="exampleInputEmail1" aria-describedby="emailHelp" name="email" placeholder="Enter email">
                    </div>
                    <button type="submit" class="btn btn-primary">Submit</button>
                </form>
            </div>
        </div>
</body>
</html>

Edit views/users/edit.ejs file, and add the following code to it:

<!DOCTYPE html>
<html>
<head>
    <title>Node.js update Data from Html Form to Mongodb Database - Tutsmake.com</title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
</head>
<body>
    <form action="/users/update/<%= data._id %>" method="post" name="form1">
        <div class="form-group">
            <label for="exampleInputPassword1">Name</label>
            <input type="text" class="form-control" name="name" id="name" value="<%= data.name %>" placeholder="Name">
        </div>
        <div class="form-group">
            <label for="exampleInputEmail1">Email address</label>
            <input type="email" class="form-control" name="email" id="email" aria-describedby="emailHelp" placeholder="Enter email" value="<%= data.email %>">
        </div>
        <button type="submit" class="btn btn-info">Update</button>
    </form>
</body>
</html>

Step 5 – Import Modules in App.js

Import express flash session body-parser mongoose dependencies in app.js; as shown below:

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var bodyParser = require('body-parser');
var flash = require('express-flash');
var session = require('express-session');
var usersRouter = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({
    extended: false
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({
    secret: '123456catr',
    resave: false,
    saveUninitialized: true,
    cookie: {
        maxAge: 60000
    }
}))
app.use(flash());
app.use('/', usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
    next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};
    // render the error page
    res.status(err.status || 500);
    res.render('error');
});
module.exports = app;

Step 7 – Test CRUD Application

You can use the following command to start node js app server:

//run the below command

npm start

Type the following URL in browser for testing:

http://127.0.0.1:3000/

Conclusion

Node js crud mongodb example; In this tutorial you have learned how to create crud operations in node js express and mongodb mongoose.

Recommended Node JS Tutorials

AuthorDevendra Dode

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

Your email address will not be published. Required fields are marked *