Home > DeveloperSection > Articles > CRUD Operation in Node.js with MongoDB

CRUD Operation in Node.js with MongoDB


Node.JS Node JS  MongoDB 
Ratings:
0 Comment(s)
 8099  View(s)
Rate this:

CRUD Operation in Node.js with MongoDB


In this article, I’m explaining the CRUD operation in node.js. In the CRUD operation come the Create, Read, Update and Delete operation. I give the very simple example of student that perform the crud operation.

 

This article is written for node.js express project. There are following steps to follow to create the CRUD operation in node.js.

Step 1 Create express project

 

First we create the where we want to store it. First, open your command prompt with administrator and change the location where you want. Here, we select location as ‘D:\node’. As give below:

CRUD Operation in Node.js with MongoDB

Here type the location and hit the enter key from your keyboard. Then after you create the express project with the name CRUD_Operation_Project. Here see the how to do:

CRUD Operation in Node.js with MongoDB

And hit enter key from the keyboard create your express project successfully.

 

Step 2 Install Dependencies

 

If you create the express project then you should must install decencies to connect with database or anything. If you would not install decencies get the error. To install the dependencies open up the package.json from the project D:\node\CRUD_Operation_Project\pacjkage.json.

{

  "name": "CRUD_Operation_Project",

  "version": "0.0.1",

  "private": true,

  "scripts": {

    "start": "node ./bin/www"

  },

  "dependencies": {

    "express": "~4.2.0",

    "static-favicon": "~1.0.0",

    "morgan": "~1.0.0",

    "cookie-parser": "~1.0.1",

    "body-parser": "~1.0.0",

    "debug": "~0.7.4",

    "jade": "~1.3.0"

 }

}

 

And add few lines in this code as like this:

{

  "name": "CRUD_Operation_Project",

  "version": "0.0.1",

  "private": true,

  "scripts": {

    "start": "node ./bin/www"

  },

  "dependencies": {

    "express": "~4.2.0",

    "static-favicon": "~1.0.0",

    "morgan": "~1.0.0",

    "cookie-parser": "~1.0.1",

    "body-parser": "~1.0.0",

    "debug": "~0.7.4",

    "jade": "~1.3.0",

    "mongodb": "*",

   "mongoskin": "*"

  }

}

 

 After that you must install from the NPM as like this:

CRUD Operation in Node.js with MongoDB

Hit enter key from keyboard it take the few minutes and install the some necessary package.

 

Step 3 Create Database and Add Some Data

 

First of all you create a directory as data in your project that store the database. Create the data folder from command prompt.

CRUD Operation in Node.js with MongoDB

After that you open a new command prompt with administrator change the location where you install the mongodb. And type this:

CRUD Operation in Node.js with MongoDB

Hit enter from your keyboard It established the connection of mongodb server. After this you will need to a next command prompt to run mongo command. This is like as:

CRUD Operation in Node.js with MongoDB

It give the message ‘connecting to: test’ to successfully connected then you create the database with the name nodetest database as following command:

use nodetest 

 

Now we're using the database ‘nodetest . Like with "test", nothing actually exists yet. To make the database exist, we have to add some data. We're going to start off by doing that right inside of the Mongo client. Let's add one and see how it works. In your Mongo client, type this:

db.studentcollection.insert({ "st_id":1000,"fullname" : "Amit Singh", "email" : “amit@testdomain.com", "age":27,"address":"Allahabad","gender":"Male" })

 

We can also add the pair of records by using array like this:

newstuff = [{ "st_id":1001,"fullname" : "Anil Kumar", "email" : "anil@testdomain.com", "age":24,"address":"Allahabad","gender":"Male" }, { "st_id":1002,"fullname" : "Atul Kumar", "email" : "atul@testdomain.com", "age":25,"address":"Allahabad","gender":"Male" }]

db.studentcollection.insert(newstuff);

 

Let’s move to show the data using db.studentcollection.find().pretty() as like this:

CRUD Operation in Node.js with MongoDB

You have successfully add data in the database using JSON structure.

 

Step 4 Starting with HTML

 

If we're going to have a single-page web app, the first thing we need is a single page, right? Let's open up our views folder, and start with layout.jade. This is a template file that we're only going to make a few basic changes to. Here's how it starts:

doctype html

html

  head

    title= title

    link(rel='stylesheet', href='/stylesheets/style.css')

  body

    block content

 

We want to be able to do two things. One: include jQuery, and two: include our master javascript file. So let's edit the file and make it look like this:

doctype html

html

    head

        title= title

        link(rel='stylesheet', href='/stylesheets/style.css')

    body

        block content

        script(src='http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js')

        script(src='/javascripts/global.js')

 

Astute readers may note that global.js does not actually exist yet. This is true. We're going to make it in a bit. For now, it'll just quietly 404 in the background when we load our index page. If this really bothers you, feel free to create an empty file now in /public/javascripts/.

Include the css to look good in /public/stylesheets/style.css copy the css code from give below and paste it into the style.css file:

body {

  padding: 30px;

  font: 14px "Lucida Grande", Helvetica, Arial, sans-serif;

}

 

h2 {

                margin:0 0 .5em 0;

}

 

a {

  color: #00B7FF;

}

 

#wrapper {

                padding-left:312px;

                position:relative;

}

 

#studentList {

                margin:0 0 30px 0;

}

                #studentList table {

                                border-collapse:separate;

                                border-spacing:1px;

                                background:#CCC;

                }

                                #studentList table th {

                                                background:#EEE;

                                                font-weight:600;

                                                padding:10px 20px;

                                                text-align:center;

                                }

                                #studentList table tbody {

                                                padding:0; margin:0;

                                                border-collapse:collapse;

                                                border-spacing:0px;

                                }

                                                #studentList table td {

                                                                background:#FFF;

                                                                padding:5px 10px;

                                                                text-align:center;

                                                }

 

#studentInfo {

                width:250px;

                position:absolute;

                top:0; left:0;

}

                #studentInfo p {

                                padding:15px;

                                border:1px solid #CCC;

                                background:rgba(80,120,255,0.05);

                }

 

fieldset {

                border:0;

                padding:0; margin:0;

}

 

Open index.jade. You'll see a VERY basic skeleton here:

extends layout

 

block content

  h1= title

  p Welcome to #{title}

 

You will create a student list, student info, and add student, update student in the page as the following code. This code copy and replace in the index.jade file.

extends layout

 

block content

    h1= title

    p Welcome to our test

 

    // Wrapper

    #wrapper

 

        // Student INFO

        #studentInfo

            h2 Student Info

            p

                strong Name:

                |  <span id='studentInfoName'></span>

                br

                strong Age:

                |  <span id='studentInfoAge'></span>

                br

                strong Gender:

                |  <span id='studentInfoGender'></span>

                br

                strong Location:

                |  <span id='studentInfoLocation'></span>

        // /Student INFO

 

        // Student LIST

        h2 Student List

        #studentList

            table

             thead

               th Student ID

               th Student Name

               th Email

               th Delete?

               tbody

        // /Student LIST

 

        //ADD OR Update Student

        h2 Add Student

        #addStudent

            fieldset

               table

                tbody

                  tr

                   th ID

                   td

                     input#inputStudentID(type='text', placeholder='Student ID')

                   th Name

                   td

                     input#inputStudentFullName(type='text', placeholder='Name')

                  tr

                   th Age

                   td

                     input#inputStudentAge(type='text', placeholder='Age')

                   th Location

                   td

                     input#inputStudentAddress(type='text', placeholder='Location')

                  tr

                   th Gender

                   td

                     input#inputStudentGender(type='text', placeholder='Gender')

                   th Email

                   td

                     input#inputStudentEmail(type='text', placeholder='Email')

                  tr

                   td

                   td

                   td

                     button#btnAddStudent Add Student

                   td

                     button#btnUpdateStudent Update Student

      // /ADD OR Update Student

 

    // /WRAPPER

 

After that start the server using the following command:

npm start

 

Let’s run on the browser at the address http://localhost:3000/ and it’s looking nice.

CRUD Operation in Node.js with MongoDB

 

Step 5 Listing Students

 

It's time to start making changes to app.js, the heart and soul of our application. Add some new code to in the app.js file after these lines:

var express = require('express');

var path = require('path');

var favicon = require('static-favicon');

var logger = require('morgan');

var cookieParser = require('cookie-parser');

var bodyParser = require('body-parser');

 

// New Database lines

var mongo = require('mongoskin');

var db = mongo.db("mongodb://localhost:27017/nodetest", {native_parser:true});

 

After six lines where commented New Database lines. That two lines connection established with database with your application.

We also need to make our database accessible to our various http requests, as we did in the first tutorial. To do that, first find this section:

app.use('/', routes);

app.use('/users', users);

 

And just above it, add this code:

// Make our db accessible to our router

app.use(function(req,res,next){

    req.db = db;

    next();

}); 

 

Now it’s time to move on to the routing. Note that Express auto-creates a /users route file. We're going to make use of that, but we won't be creating any views for it. Why? Well, because since this is a single-page app, we're using the Index route and view for display purposes. We're going to use the user route to set up our data I/O … the services we want to create to show, add, and delete users from our database.

So open up routes/User.js replace all code with the given code as below:

var express = require('express');

var router = express.Router();

 

/*

 * GET studentlist.

 */

router.get('/studentlist', function(req, res) {

    var db = req.db;

    db.collection('studentcollection').find().toArray(function (err, items) {

        res.json(items);

    });

});

 

module.exports = router;

 

The purpose of this code is: if you do an HTTP GET to /users/studentlist, our server will return JSON that lists all of the users in the database. Obviously for a large-scale project you'd want to put in limits as to how much data gets spewed out at one time, for example by adding paging to your front-end, but for our purposes this is fine.

Let’s start to define the function to populate our HTML tables with data. To define this function to create a GLOBAL.js file under the /public/javascripts folder. Let’s create a GLOBAL.js file and add following code:

// Studentlist data array for filling in info box

var studentListData = [];

 

// DOM Ready =============================================================

$(document).ready(function() {

 

    // Populate the Student table on initial page load

    populateTable();

});

 

// Functions =============================================================

 

// Fill table with data

function populateTable() {

 

    // Empty content string

    var tableContent = '';

 

    // jQuery AJAX call for JSON

    $.getJSON( '/users/studentlist', function( data ) {

 

        // For each item in our JSON, add a table row and cells to the content string

        $.each(data, function(){

            tableContent += '<tr>';

                                                tableContent += '<td>' + this.st_id + '</td>';

            tableContent += '<td><a href="#" class="linkshowstudent" rel="' + this.fullname + '" title="Show Details">' + this.fullname + '</a></td>';

            tableContent += '<td>' + this.email + '</td>';

            tableContent += '<td><a href="#" class="linkdeletestudent" rel="' + this._id + '">delete</a></td>';

            tableContent += '</tr>';

                                                // Stick our user data array into a studentlist variable in the global object

                                               

        });

        // Inject the whole content string into our existing HTML table

        $('#studentList table tbody').html(tableContent);

    });

};

 

This code populate html table with the data. Save your GLOBAL.js file, kill your node instance if it's still running, and restart it with

npm start

 

Let’s start to ready to show the student list in the browser from your database. See on the browser at http://localhost:8000/ as like this:

CRUD Operation in Node.js with MongoDB

 

Step 6 Populating the Student Info

 

Still working in GLOBAL.js, we need to add a line in the populateTable() function to store the data into a global array list. You need to add some code after this code:

  // jQuery AJAX call for JSON

    $.getJSON( '/users/studentlist', function( data ) {

 

        // For each item in our JSON, add a table row and cells to the content string

        $.each(data, function(){

 

After the end the $.each function add this code:

// Stick our user data array into a studentlist variable in the global object

studentListData = data;

 

studentListData is the global array that store all the data of student which show by the populateTable() function.

Now add the function to show student information to show a particular student information. That information show as on demand click on link of Student Name. Let’s add a function to show information:

// Show Student Info

function showStudentInfo(event) {

 

    // Prevent Link from Firing

    event.preventDefault();

 

    // Retrieve username from link rel attribute

    var thisStudentName = $(this).attr('rel');

 

    // Get Index of object based on id value

    var arrayPosition = studentListData.map(function(arrayItem) { return arrayItem.fullname; }).indexOf(thisStudentName);

 

    // Get our Student Object

    var thisStudentObject = studentListData[arrayPosition];

 

    //Populate Info Box

    $('#studentInfoName').text(thisStudentObject.fullname);

    $('#studentInfoAge').text(thisStudentObject.age);

    $('#studentInfoGender').text(thisStudentObject.gender);

    $('#studentInfoLocation').text(thisStudentObject.address);

 

};

 

Now we need to trigger this function at link of student name. So add the following code DOM ready section to call above function:

// Student Name link click

    $('#studentList table tbody').on('click', 'td a.linkshowstudent', showStudentInfo);

 

Now let’s run on the browser and see that o click of student name. It’s fantastic:

CRUD Operation in Node.js with MongoDB

 

Step 7 Add New Student

 

In this article already create layout for student info, student list, and also add new student or update the student. So here don’t need to waste time in the layout.  Now need to add few lines of code under the User.js /routes to insert the new student:

/*

 * POST to addstudent.

 */

router.post('/addstudent', function(req, res) {

    var db = req.db;

    db.collection('studentcollection').insert(req.body, function(err, result){

        res.send(

            (err === null) ? { msg: '' } : { msg: err }

        );

    });

});

 

It must be add above the module.exports. Now need to add a function add new student and show in the table after added. Add a function in the /public/javascripts/GLOBAL.js:

// Add Student

function addStudent(event) {

    event.preventDefault();

 

    // Super basic validation - increase errorCount variable if any fields are blank

    var errorCount = 0;

    $('#addStudent input').each(function(index, val) {

        if($(this).val() === '') { errorCount++; }

    });

 

    // Check and make sure errorCount's still at zero

    if(errorCount === 0) {

 

        // If it is, compile all student info into one object

        var newStudent = {

            'st_id': $('#addStudent fieldset input#inputStudentID').val(),

            'fullname': $('#addStudent fieldset input#inputStudentFullName').val(),

            'age': $('#addStudent fieldset input#inputStudentAge').val(),

            'address': $('#addStudent fieldset input#inputStudentAddress').val(),

            'gender': $('#addStudent fieldset input#inputStudentGender').val(),

                                                'email': $('#addStudent fieldset input#inputStudentEmail').val()

        }

 

        // Use AJAX to post the object to our addStudent service

        $.ajax({

            type: 'POST',

            data: newStudent,

            url: '/users/addstudent',

            dataType: 'JSON'

        }).done(function( response ) {

 

            // Check for successful (blank) response

            if (response.msg === '') {

 

                // Clear the form inputs

                $('#addStudent fieldset input').val('');

 

                // Update the table

                populateTable();

 

            }

            else {

 

                // If something goes wrong, alert the error message that our service returned

                alert('Error: ' + response.msg);

 

            }

        });

    }

    else {

        // If errorCount is more than 0, error out

        alert('Please fill in all fields');

        return false;

    }

};

 

Now need to this function call. So this function call add a line to DOM ready section:

// Add Student button click

    $('#btnAddStudent').on('click', addStudent);

 

Save all changes and now test to add new student let’s see on the browser at http://localhost:8000/:

CRUD Operation in Node.js with MongoDB

Now click on the Add Student button look it simply add new student. After the add new student in the database show the student list as updated in the page as like this:

CRUD Operation in Node.js with MongoDB

Now you successfully add a new student.

 

Step 8 Update Student

 

In this section update the student record. Here do not need more thing it is like as addstudent but some diffrences. Let’s now add the code in User.js above of module.exports:

/*

 * POST to updatestudent.

 */

router.post('/updatestudent', function(req, res) {

    var db = req.db;

    var studentToUpdate=req.params.id;

    db.collection('studentcollection').update({id:studentToUpdate},req.body, function(err, result){

        res.send(

            (err === null) ? { msg: '' } : { msg: err }

        );

    });

})

 

Here update on the basis of unique id in the update function now let’s move on the global.js file and some code to update function. First of all need to showStudentInfo function to show on the textbox fields which student you want to update as following:

// Show Student Info

function showStudentInfo(event) {

 

    // Prevent Link from Firing

    event.preventDefault();

 

    // Retrieve username from link rel attribute

    var thisStudentName = $(this).attr('rel');

 

    // Get Index of object based on id value

    var arrayPosition = studentListData.map(function(arrayItem) { return arrayItem.fullname; }).indexOf(thisStudentName);

 

    // Get our Student Object

    var thisStudentObject = studentListData[arrayPosition];

 

    //Populate Info Box

    $('#studentInfoName').text(thisStudentObject.fullname);

    $('#studentInfoAge').text(thisStudentObject.age);

    $('#studentInfoGender').text(thisStudentObject.gender);

    $('#studentInfoLocation').text(thisStudentObject.address);

 

    // New Code show student information in textbox

    $('#addStudent fieldset input#inputStudentID').val(thisStudentObject.st_id);

    $('#addStudent fieldset input#inputStudentFullName').val(thisStudentObject.fullname);

    $('#addStudent fieldset input#inputStudentAge').val(thisStudentObject.age);

    $('#addStudent fieldset input#inputStudentAddress').val(thisStudentObject.address);

    $('#addStudent fieldset input#inputStudentGender').val(thisStudentObject.gender);

    $('#addStudent fieldset input#inputStudentEmail').val(thisStudentObject.email);

};

 

In the above code just only those code which are comment as ‘New Code show student information in textbox’. It show to the textbox that want to update.

Let’s now need to add a function update functionality:

// Update Student

function updateStudent(event) {

    event.preventDefault();

 

    // Super basic validation - increase errorCount variable if any fields are blank

    var errorCount = 0;

    $('#addStudent input').each(function(index, val) {

        if($(this).val() === '') { errorCount++; }

    });

 

    // Check and make sure errorCount's still at zero

    if(errorCount === 0) {

 

        // If it is, compile all student info into one object

        var modifiedStudent = {

            'st_id': $('#addStudent fieldset input#inputStudentID').val(),

            'fullname': $('#addStudent fieldset input#inputStudentFullName').val(),

            'age': $('#addStudent fieldset input#inputStudentAge').val(),

            'address': $('#addStudent fieldset input#inputStudentAddress').val(),

            'gender': $('#addStudent fieldset input#inputStudentGender').val(),

                                                'email': $('#addStudent fieldset input#inputStudentEmail').val()

        }

 

        // Use AJAX to post the object to our updateStudent service

        $.ajax({

            type: 'POST',

            data: modifiedStudent,

            url: '/users/updatestudent',

            dataType: 'JSON'

        }).done(function( response ) {

 

            // Check for successful (blank) response

            if (response.msg === '') {

 

                // Clear the form inputs

                $('#addStudent fieldset input').val('');

 

                // Update the table

                populateTable();

 

            }

            else {

 

                // If something goes wrong, alert the error message that our service returned

                alert('Error: ' + response.msg);

 

            }

        });

    }

    else {

        // If errorCount is more than 0, error out

        alert('Please fill in all fields');

        return false;

    }

};

 

This function post data of student in the json format and it need to call it into the DOM ready section:

// Update Student button click

    $('#btnUpdateStudent').on('click', updateStudent);

 

After that all these things save all the changes and now reastart the server by npm start:

npm start

 

Ready to run the browser at http://localhost:8000/ for test the update operation in a single page. So test it:

When click on student name link the student information populated but also population in the textbox’s.
CRUD Operation in Node.js with MongoDB

 

Let’s change some information like Age: 26 to 23,  Location: Allahabad to Varanashi after that click on ‘Update Student’ to update the infomartion

CRUD Operation in Node.js with MongoDB

Let’s check it click on the Student Name: Manoj link and check the information:

CRUD Operation in Node.js with MongoDB

Yes! It’s working. Update function works successfully.

 

Step 9 Deleting Student

 

In this section delete a student or remove from the record. This is much easier to add a new student. Let's start with the route file. Update: the syntax has changed since I first posted this tutorial. The NEW, correct syntax is shown here. Open /routes/users.js and add the following to the bottom, just above module.exports:

/*

 * DELETE to deletestudent.

 */

router.delete('/deletestudent/:id', function(req, res) {

    var db = req.db;

    var studentToDelete = req.params.id;

    db.collection('studentcollection').removeById(studentToDelete, function(err, result) {

        res.send((result === 1) ? { msg: '' } : { msg:'error: ' + err });

    });

});

 

Save /routes/users.js and then we'll wire stuff up in the JavaScript. Let's move back to global.js. We've already populated each delete link with a rel attribute that contains the id. It's in this line from global.js:

tableContent += '<td><a href="#" class="linkdeletestudent" rel="' + this._id + '">delete</a></td>';

 

Now we add a new function to delete it:

// Delete Student

function deleteStudent(event) {

 

    event.preventDefault();

 

    // Pop up a confirmation dialog

    var confirmation = confirm('Are you sure you want to delete this user?');

 

    // Check and make sure the user confirmed

    if (confirmation === true) {

 

        // If they did, do our delete

        $.ajax({

            type: 'DELETE',

            url: '/users/deletestudent/' + $(this).attr('rel')

        }).done(function( response ) {

 

            // Check for a successful (blank) response

            if (response.msg === '') {

            }

            else {

                alert('Error: ' + response.msg);

            }

 

            // Update the table

            populateTable();

 

        });

 

    }

    else {

 

        // If they said no to the confirm, do nothing

        return false;

 

    }

 

};

 

Now need to call the delete function add the DOM ready section:

// Delete Student link click

    $('#studentList table tbody').on('click', 'td a.linkdeletestudent', deleteStudent);

Remember to restart your node server and then hit http://localhost:3000 to test it out.

CRUD Operation in Node.js with MongoDB

 

Confirm to delete the will perform. Here, student Manoj deleted from the list:

CRUD Operation in Node.js with MongoDB

Here the successfully deleted the student from the database and the table.

 

I hope that this article for CRUD operation is helpful for you. Thanks!


Don't want to miss updates? Please click the below button!

Follow MindStick