articles

Home / DeveloperSection / Articles / MongoDB with Node.js

MongoDB with Node.js

Anchal Kesharwani8315 19-Aug-2014

In this article, I’m explaining how to work node.js with mongodb. Here, I give a simple example to understand it.

If you want learn how to create an express project in node.js first, then you can read my article using the below link:

Create Express Project in Node.js

Below article link will tell you how to install and setup MongoDB:

Install and Setup MongoDB

Node.js and the MongoDB are both follow JSON structure. MongoDB is a very lightweight database. Here, I create an example of node.js with mongodb. There are following steps to create a project.

Step 1 Run Mongod and Mongo

In the previous article Create an express Project in node.js, we a create a project nodejstest. So we continue with mongodb. In your nodejstest directory create subdirectory data. Then navigate to the directory in which you placed your MongoDB files (let's say C:\Program Files\MongoDB 2.6 Standard\bin for now). From that directory, type the following:

MongoDB with Node.js

And Hit the enter button. You'll see the Mongo server start up. This is going to take a while if it's the first time, because it has to do some preallocating of space and a few other housekeeping tasks. Once it says "[initandlisten] waiting for connections on port 27017", you're good. There's nothing more to do here; the server is running. Now you need to open a second command prompt. Navigate again to your Mongo installation directory, and type and hit the enter button:

MongoDB with Node.js

Additionally, if you're paying attention to your mongod instance, you'll see it

mention that a connection has been established. Let’s create a database for a

project and work a little bit with mongod.

 

Step 2 Create a Database

 

Don’t worry to ‘connecting to: test’. No need to open another command prompt

which command prompt run the mongo command create a database as test

database. To create a database type the following code and hit the enter key:

 

MongoDB with Node.js

Now we're using the database "nodejstest." 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.

Step 3 Add Some Data

 

It’s really fantastic about MongoDB is that it uses JSON for its structure, which

means it was instantly familiar for me.

Let's add a record to our collection. For the purposes of this tutorial, we're just

going to have a simple database of fullname, email, age, address, and age. Our

data format will thus look like this:

{ 
    "_id" : 1224,
    "fullname" : "Employee1",
    "email" : "testemp1@gmail.com",
     "age":27,
     "address":"Allahabad",
     "gender":"Male"

 

You can create your own _id assignment if you really want, but I find it's best to let

Mongo just do its thing. It will provide a unique identifier for every single top-level

collection entry. Let's add one and see how it works. In your Mongo client, type this:

db.empcollection.insert({ "fullname" : "Employee1", "email" : "testemp1@testdomain.com", "age":27,"address":"Allahabad","gender":"Male" }) 

In the nodejstest database add the empcollction and when it first time add it auto

create the collection that means table. Assuming everything went right, you should

see … nothing. That's not very exciting, so type this:

db.empcollection.find().pretty() 

In case you're curious, the .pretty() method gives us line breaks. It will return:

MongoDB with Node.js

Except, of course, your ObjectID will be different, since as mentioned, Mongo is

automatically generating those. Now that we've got one record, let's add couple

more. In your Mongo console, type the following:

newstuff = [{ "fullname" : "Employee2", "email" : "testemp2@testdomain.com", "age":24,"address":"Allahabad","gender":"Male" }, { "fullname" : "Employee3", "email" : "testemp2@testdomain.com", "age":23,"address":"Allahabad","gender":"Male" }]

db.empcollection.insert(newstuff); 

 

Note that we pass the array and it contains two records. So we have total number

of records. Let we check that from db.empcollection.find().pretty():

MongoDB with Node.js

 

Now we're going to start actually interacting with the web server and site that we

set up earlier.

Step 4 Mongo to node

 

This is where the rubber meets the road. Let's start by building a page that just

spits out our DB entries in a mildly pretty form. Here's the HTML we're shooting to

generate:

<ul> 
    <li><span>Employee1</span></li>
    <li><span>Employee2</span></li>
    <li><span>Employee3</span></li>
</ul> 

 

First we open the app.js from d:\node\nodejstest\app.js file and add some few lines

to connect with the mongodb. Let we see how to add 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 Code
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/nodejstest'); 

 

Where the comment New code this code establish the connection of mongodb

and connect with the database.

We need add some extra code in the app.js. we need to add custom function

before the route definition.

// Make our db accessible to our router 
app.use(function(req,res,next){
    req.db = db;
    next();
});

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

 

Where comment the Make our db accessible to our router this is custom function

to need to add this position.

NOTE: If you don't put this above the routing stuff mentioned above (app.use('/',

routes);), your app WILL NOT WORK. 

Step 5 Show Data from Database

 

Now, Open up D:\node\nodejstest\routes\index.js and add a page userlist for

employee. Let’s add it:

/* GET Employeelist page. */

 

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

    var db = req.db;

    var collection = db.get('empcollection');

    collection.find({},{},function(e,docs){

        res.render('userlist', {

            "userlist" : docs

        });

    });

}); 

 

Next let's set up our Jade template. Navigate to C:\node\nodetest1\views\ and open

index.jade. Once again, immediately save it as userlist.jade. Then edit the HTML so it

looks like this:

extends layout

 

block content

    h1.

        Employee List

    ul

        each user, i in userlist

            li

                span= user.fullname 

 

We're all set. Save that file, and let's restart our node server. Remember how to do

that? Go to your command prompt, head for C:\node\nodejstest\ and ctrl-c to kill

your server if it's still running from way back before. Then type:

npm  start 

Now open your browser and head to http://localhost:3000/userlist and marvel in

the results.

MongoDB with Node.js

 

You're now pulling data from the DB and spitting it out onto a web page. Nice!

Now we need write to data in the database from the data input.

Step 6 Insert Data to Database

 

Writing to the database is not particularly difficult. Essentially we need to set up a

route that takes a POST, rather than a GET.

We're going quick and dirty here: two ugly, unstyled text inputs and a submit

button. 1996-style, but before we get to that, we're going to do some javacripting.

Let's start by quickly wiring up a route for our add user form. Open /routes/index.js

and add the following code above the last module.exports line:

/* GET New Employee page. */

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

    res.render('newemployee', { title: 'Add New Employee' });

}); 

 

Now we just need a template. Open up /views/index.jade, save it as newuser.jade,

and replace the whole file contents with this:

extends layout

 

block content

    h1= title

    form#formAddEmployee(name="addEmployee",method="post",action="/addEmployee")

        input#inputEmployeeFullName(type="text", placeholder="Name", name="name")

        input#inputEmployeeEmail(type="text", placeholder="Email ID", name="email")

        input#inputEmployeeAge(type="text", placeholder="Age", name="age")

        input#inputEmployeeAddress(type="text", placeholder="Address", name="address")

        input#inputEmployeeGender(type="text", placeholder="Gender", name="gender")

        button#btnSubmit(type="submit") submit 

 

Here form id is “formAddEmployee” and action is “addEmployee”.

If you restart your node server and go to http://localhost:3000/newemployee you'll

see your form in all its glory.

MongoDB with Node.js

 

Step 6 Create Your Database Functions

 

Go back to /routes/index.js and let's create our insertion function. Once again, you'll

want to put this above the final module.exports line (it doesn't REALLY matter, but

it makes things cleaner to wrap up with the export). This is a big one, so I've

commented the code pretty thoroughly. Here it is:

/* POST to Add Employee Service */

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

 

    // Set our internal DB variable

    var db = req.db;

 

    // Get our form values. These rely on the "name" attributes

    var empName = req.body.name;

    var empEmail = req.body.email;

                var empAge=req.body.age;

                var empAddress=req.body.address;

                var empGender=req.body.gender;

 

    // Set our collection

    var collection = db.get('empcollection');

 

    // Submit to the DB

    collection.insert({

        "fullname" : empName,

                                "email" : empEmail,

                                "age":empAge,

                                "address":empAddress,

                                "gender":empGender

    }, function (err, doc) {

        if (err) {

            // If it failed, return error

            res.send("There was a problem adding the information to the database.");

        }

        else {

            // If it worked, set the header so the address bar doesn't still say /addEmployee

            res.location("userlist");

            // And forward to success page

            res.redirect("userlist");

        }

    });

}); 

 

Here no validation for the email or duplicate name or anything. Here, just we write

the code to add employee information.

We need to restart the server then we stop the server using Ctrl+C and then type this:

npm start 

Assuming your server is running, which it should be, return to your web browser

and point it at http://localhost:3000/newemployee again. There's our exciting form,

just like before. Let’s enter the employee information and click on the submit

button that redirect to userlist page.

MongoDB with Node.js

When click the submit button. You will see that that:

MongoDB with Node.js

The last employee is Ajay that was add in the last.

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


Updated 07-Sep-2019

Leave Comment

Comments

Liked By