CRUD Operations In Node.JS Using MongoDB

In this article, we will learn about how we can perform CRUD operations in Node.js using MongoDB.

If you are looking for Node.JS CRUD With SQL Server please click here.

Prerequisites:

  • Basic knowledge of Node.js and MongoDB
  • Code editor like Visual Studio 2019

If you’re new to Node.js? You must have to follow the link given below to set up a new Node.js App in Visual Studio.

How To Create Node.js App In Visual Studio

Create, Read, Update, and Delete operations in Node.js

First, right-click the project name in the Solution Explorer and select Add -> New Folder (Database).

Now, right-click the folder name (Database) in the Solution Explorer and select Add -> New File… (dbConnection.js).

Open the dbConnection.js file and add the code to it.

var mongoose = require('mongoose');
mongoose.connect('mongodb://127.0.0.1:27017/StudentDB');

var studentInfoSchema = mongoose.Schema({
    name: String,
    age: Number
});

mongoose.model("StudentInfo", studentInfoSchema, "student_info");

exports.use = function (modelName) {
    return mongoose.model(modelName);
};

Now, we have to install a package to connect MongoDB Server.

Install the mongoose package with the NPM:

Right-click on the npm from Solution Explorer -> Install New npm Packages…

Search and install the mongoose package.

Open the index.js file from the routes folder and add the code to it.

'use strict';
var express = require('express');
var router = express.Router();
var db = require('../Database/dbConnection');

/* Get All Students */
router.get('/', function (req, res) {
    db.use("StudentInfo").find(function (err, response) {
        if (err) {
            console.log(err)
        }
        res.render('index', { studentList: response }) //res.render() pass a local variable to the view
    });
});

/* Add Student */
router.post('/addStudent', function (req, res) {
    db.use("StudentInfo").create({
        name: req.body.txtName,
        age: req.body.txtAge
    }, function (err) {
        if (err) {
            console.log(err)
        }
        res.redirect('back')
    });
});

/* Delete Student */
router.get('/deleteStudent/:ID', function (req, res) {
    db.use("StudentInfo").findByIdAndRemove(req.params.ID, function (err) {
        if (err) {
            console.log(err)
        }
        res.redirect('back')
    });
});

/* Edit Student */
router.get('/editStudent/:ID', function (req, res) {
    db.use("StudentInfo").findById(req.params.ID, function (err, response) {
        if (err) {
            console.log(err)
        }
        res.send(response)
    });
});

/* Update Student */
router.post('/updateStudent', function (req, res) {
    db.use("StudentInfo").findByIdAndUpdate(req.body.txtID, {
        name: req.body.txtEName,
        age: req.body.txtEAge
    }, function (err) {
        if (err) {
            console.log(err)
        }
        res.redirect('back')
    });
});


module.exports = router;
  • Get All Students, returns all the records from the StudentInfo collection when the home page is loaded successfully.
  • Add Student, inserts a new document in the StudentInfo collection.
  • Delete Student, removes a document from the StudentInfo collection.
  • Edit Student, returns a single document from the StudentInfo collection based on ID, later it can be used to update Student Info.
  • Update Student, updates a selected document in the StudentInfo collection.

 

Open the index.html file from the views folder and add the code in it.

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
</head>
<body>
    <div class="container">
        <div class="row">
            <div class="col-md-6">
                <h3 class="text-center">Add Student</h3>
                <!-- Inserts a new record in the StudentInfo collection -->
                <form action="addStudent" method="post">
                    <div class="form-group">
                        <label for="txtName">Name:</label>
                        <input class="form-control" placeholder="Enter name" id="txtName" name="txtName">
                    </div>
                    <div class="form-group">
                        <label for="txtAge">Age:</label>
                        <input type="number" class="form-control" placeholder="Enter age" id="txtAge" name="txtAge">
                    </div>
                    <button type="submit" class="btn btn-primary">Submit</button>
                </form>
            </div>
            <div class="col-md-6">
                <h3 class="text-center">Student List</h3>
                <table class="table table-bordered">
                    <thead class="thead-dark">
                        <tr>
                            <th>ID</th>
                            <th>Name</th>
                            <th>Age</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <!-- Display list of records from the StudentInfo collection -->
                        <% for (const i in studentList) { %>
                        <tr>
                            <td><%= studentList[i].id %></td>
                            <td><%= studentList[i].name %></td>
                            <td><%= studentList[i].age %></td>
                            <td width="200px">
                                <a href="deleteStudent/<%= studentList[i].id %>">Delete</a>
                                &emsp; | &emsp;
                                <a onclick="editStudent('<%= studentList[i].id %>')" href="javascript:void(0)" data-toggle="modal" data-target="#editModal">Edit</a>
                            </td>
                        </tr>
                        <% } %>
                    </tbody>
                </table>
                <!-- Edit Student Modal -->
                <div class="modal fade" id="editModal">
                    <div class="modal-dialog modal-dialog-centered">
                        <div class="modal-content">
                            <!-- Modal Header -->
                            <div class="modal-header">
                                <h4 class="modal-title">Edit Student</h4>
                                <button type="button" class="close" data-dismiss="modal">&times;</button>
                            </div>
                            <form action="updateStudent" method="post">
                                <!-- Modal body -->
                                <div class="modal-body">
                                    <input type="hidden" id="txtID" name="txtID">
                                    <div class="form-group">
                                        <label for="txtEName">Name:</label>
                                        <input class="form-control" placeholder="Enter name" id="txtEName" name="txtEName">
                                    </div>
                                    <div class="form-group">
                                        <label for="txtEAge">Age:</label>
                                        <input type="number" class="form-control" placeholder="Enter age" id="txtEAge" name="txtEAge">
                                    </div>
                                </div>
                                <!-- Modal footer -->
                                <div class="modal-footer">
                                    <button type="submit" class="btn btn-primary">Update</button>
                                    <button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <script>
        function editStudent(id) {
            // AJAX call to select a record in the editable modal popup
            $.ajax({
                url: 'editStudent/' + id,
                type: 'GET',
                success: function (res) {
                    $("#txtID").val(res._id);
                    $("#txtEName").val(res.name);
                    $("#txtEAge").val(res.age);
                },
                error: function (err) {
                    alert(err);
                }
            });
        }
    </script>
</body>
</html>

Here, we used Bootstrap 4 for responsive design.

Output:

 

Please give your valuable feedback and if you have any questions or issues about this article, please let me know. Don’t forget to check the comments mentioned in the code given above for a better understanding.

Also, check Binding DropDownList With MongoDB In Node.js

Submit a Comment

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

Subscribe

Select Categories