Node.js

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 >

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

Yasin Panwala

Yasin Panwala is a Web Developer and Author at TheCodeHubs. He has experience in Web Developing and Designing and also in Writing. He has got his skills in working on technologies like .NET Core, ADO.NET, AJAX, Angular, AngularJS, ASP.NET, ASP.NET MVC, Bootstrap, C#, CSS, Entity Framework, Express.js, GraphQL, HTML, JavaScript, JQuery, JSON, LINQ, Microsoft Office, MongoDB, MySQL, Node.js, PostgreSQL, SQL, SQL Server, TypeORM, TypeScript, Visual Basic .NET, Web API. He also got his skills in working with different integration and some known versioning tools. He is always ready to learn new things and he always tries his best on tasks that are assigned to him and gives the best possible outputs.

Recent Posts

Testing hk

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Operation

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

TETS NEW

test

2 years ago