Connecting MongoDB with Node Js

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

  1. Setup the mlab account

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

Create an account in mlab.com

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
    mongoose.connect('mongodb://username: password@ds243345.mlab.com:43345/diary');

//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"
    })

        sarthak.save(function(err){

            if(err) throw err;

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

        john.save(function(err){
            
                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
        console.log(users);

	});
	
	next();
});


    app.listen(3000);

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

thanks

Advertisement

One thought on “Connecting MongoDB with Node Js

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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