Before we kick start Node application lets start by creating a MongoDB database and credentials. Though creating database, could have been achieved by using Node, but that would not provide us with user & password. And I believe no one would want their database to be accessible to everyone. 😀
I hope you have got MongoDB installed on your machine, just start up the server and open command prompt.

>mongo
MongoDB shell version: 2.0.6
connecting to: test
>use supaldubey
switched to db supaldubey
>db.addUser('supal', 'key')


Lets try to understand what happened above, first we keyed in use supaldubey, this command will just prompt switched to supaldubey, but is not mandatory for mongo to create a database here.
Now we will add a user to the database, by using db.addUser(‘supal’, ‘key’). Here supal is username while key is our password.
Here we will be using MongoJS to connect to MongoDB, which is a raw low level framework, if you want more robust / ORM type framework I would recommend you mongoose.
Now you need to install the mongojs module to Node. Type the below command(obviously in your node installation directory).

sudo npm install mongojs

In case you use Windows, get rid of “sudo” 😀
Lets get started into Node I would be using the previous example’s hello.js and adding MongoDB support.

var databaseUrl = "supal:key@localhost/supaldubey";
var collections = ["users"]
var db = require("mongojs").connect(databaseUrl, collections, function(){
console.log("Connected  "+db);
});

My database URL contains the database name, as well as the authentication data. Connecting to the database is very simple, you need to just call connect with your URL, collections to be used (analogous to tables) and an call back function.
Now quickly lets add two functions to save and retrieve the users into our database.

db.users.save({name: _url.query['name'], mail: _url.query['mail']}, function(err, saved) {
if( err || !saved )
{
console.log("User not saved");
}
else
{
console.log("User saved");
}
})

Above code would read request parameters name and mail and put them into our database. Similarly we can write a function to print a list of all users in the database.

db.users.find({}, function(err, users) {
if( err || !users)
{
console.log("No users found");
}
else
{
users.forEach( function(user) {
console.log("User Found "+user.name    );
});
}
});

I will be moving the code to write to response in the call back function of db.find to ensure that all the content is written to the output stream, only when I have fetched the list of all users from the database.
Remember, Node is non blocking asynchronous Javascript.

db.users.find({}, function(err, users) {
if( err || !users)
{
console.log("No users found");
}
else
{
users.forEach( function(user) {
console.log("User Found "+user.name    );
content += "<li>"+user.name+ " = "+ user.mail +"</li>";
});
}
content += "</ul>";
response.writeHead(200, {"Content-Type": "text/html"});
response.write(content);
response.end();
});

You can grab the code from the URL here – Node + Mongo
Below is a sample run of the application just created on my laptop –
 
Node + Mongo Demo
Node + Mongo Demo Application
On the other hand – An astute reader must have noted that I have passed an empty JSON array to the function find({}). This would return all the data. We can add filtering the data returned by passing JSON arguments.
For example – If I need to print all the users with name Foo, I could have written

find({name:'foo'})

Or
If I want to limit the number of rows to 2 and skip first 3 records, I would write my function as below –

db.users.find({name:'foo'}).limit(2).skip(3);

Updates to the database can be done as below –

db.users.update({mail: "supal.dubey@roadtobe.com"}, {$set: {name: "Mongo Lover"}}, function(err, updated) {
if( err || !updated ) console.log("User not updated");
else console.log("User updated");
});

Isn’t Mongo beautiful ? 🙂
Its time to play around with the code and make more interesting Applications. Drop a comment in case you run into any issues.


2 Comments

David F · July 16, 2012 at 5:06 am

Hi,
Thanks for the tutorial, can you pls provide some more examples ? I am looking for something with more data centric operations.
Great post anyway. Looking for more.
Thanks,
Dave

Rajiv · July 25, 2012 at 1:24 pm

I’m still learning from you, while I’m trying to reach my goals. I certainly love reading all that is posted on your website.Keep the posts coming. I enjoyed it!

Leave a Reply to Rajiv Cancel reply

Avatar placeholder

Your email address will not be published.