Connecting MongoDB with Node Js

To use mongo Db with the Node Js here we can use Mongoose npm package and as mongo db cloud service provider.

  1. Setup the mlab account provides the initial 500MB free account for new users.

Create an account in

Select “Create new” in MongoDB Deployments

Click on free “Sandbox” account plan

Enter the Database name for example “diary”

DB has been created

Highlighted text shows the DB URI link by which we can connect with DB with node jS code.

Now install mongoose package in Node Js by npm install mongoose –save in CLI

Node js code is shown below to connect Node Js with Mongo DB.

2. In below code we will push/create and then retrieve two documents in DB.

    var express = require('express');
    var mongoose = require('mongoose');

    var app = express();

    //connecting to the DB

//creating a Schema
var Schema = mongoose.Schema;

    var personSchema = new Schema({

                firstname: String,
                lastname: String,
                phoneno: String,
                address: String
//creating a model
var Person = mongoose.model('Person', personSchema);

    //adding seed date 

    var sarthak = Person({

        firstname: "Sarthak",
        lastname: "Srivastava",
        phoneno: "9876543212",
        address: "DLF, Hyderabad"

            if(err) throw err;

            console.log('Person has been Saved!!!');
    var john = Person({
            firstname: "John",
            phoneno: "8769877892",
            address: "California"
                if(err) throw err;
                console.log('Person has been Saved!!!');


app.use('/', function (req, res, next) {
	console.log('Request Url:' + req.url);
	// get all the users
	Person.find({}, function(err, users) {
		if (err) throw err;
		// object of all the users



Hence when you reun localhost:3000 in your browser it will create 2 documents in mlab DB and fetches them and prints all the documents in the command prompt

and updates the mlab console



One thought on “Connecting MongoDB with Node Js

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s