Prash's Blog

Simple MongoDb example for Nodejs May 15, 2012

Filed under: Nodejs — prazjain @ 3:25 pm
Tags: , , ,

In this example we will see the interactivity between MongoDB and Nodejs.

We will create a “Post It” application in Nodejs and save the data in MongoDb.

Install npm package for async, mongoose :

npm install async mongoose

Use mongoose to interact with MongoDb in postitdb.js as below :


var util = require('util');
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var dburl = 'mongodb://localhost/postitnotes';

exports.connect = function (callback) 
{
	mongoose.connect(dburl);
};

exports.disconnect = function (callback)
{
	mongoose.disconnect(callback);
};

exports.setup = function(callback)
{
	// dummy implemetation right now, add anything else you want to do during setup
	callback(null);
};

Setup the database, create setup.js

var util = require('util');
var async = require('async');
var postitdb = require('./postitdb');

postitdb.connect(function(error)
{
	if (error) throw error;
});

postitdb.setup(function(error)
{
	if (error)
	{
		util.log('ERROR ' + error);
		throw error;
	}
	async.series([
		function(cb)
		{
			postitdb.add("2012",
				"Plans for summer 2012 concerts! Make some noise!",
				function(error)
				{
					if (error) util.log('ERROR '+ error);
					cb(error);
				});
		}
		],
		function(error, results)
		{
			if (error) util.log('ERROR ' + error);
			postitdb.disconnect(function(err) {} );
		}
		);
});

Now lets have another script just to check if the db was setup correctly

Create show.js

var util = require('util');
var postitdb = require('./postitdb');

postitdb.connect(function(error)
{
	if(error) throw error;
});

postitdb.forAll(function(error, row)
	{
		util.log('ROW : ' + util.inspect(row));
	}
	, function(error)
	{
		if (error) throw error;
		util.log('ALL DONE' );
		postitdb.disconnect(function(err) { } );
	}
);

Run mongod from MongoDb bin directory

cd c:\mongodb\bin
mongod

Now you are ready to setup database

node setup

To verify if the database was setup correctly, run show.js as below

node show

If you are able to see the record created above for 2012 plans in command prompt, then you are in good company!

We will expand on this example later to make the complete app. To be continued …

EDIT: Follow up post to make the complete Sticky Notes / Post It Application

 

4 Responses to “Simple MongoDb example for Nodejs”

  1. […] check the other post for setting up mongodb with nodejs for this […]

  2. abhimanyu05A Says:

    when I am doing node setup getting following error

    Cannot find module ‘postitdb’

  3. arjunmantri Says:

    TypeError: Object # has no method ‘insert’
    I am getting this error when i execute node setup.js


Leave a comment