Getting started with Node.js and Mongodb

Here is a post in which I try to get my arms around Node.js & MongoDB. This is first encounter with Web programming. There is a veritable universe of frameworks, languages, libraries and modules out there.

There are a gazillion blogs already on this topic so here is one more. When I came across Node.js recently,  I have been  impressed mightily with its ability to quickly cook up Webservers, TCP based server side programming and the like with really brief code. Another alluring fact was that it is based on Javascript which itself smacks of plain C, added to its charm. The experience with Node.js is difficult for a beginner. Also I must add that the Node.js’es callback functions takes a bit of getting used and I have had my share of pain with it.

MongoDB is an open-source document database, and one of the  leading NoSQL databases out there.

First things first – Install Node.js from Nodejs.org. Next install MongoDB for your OS and machine type. You will also need to install the mongodb module for use with Node.js. You can this by opening a command prompt and typing

npm install mongodb -g

This will allow you to access the mongodb module for use within your program. Now you should be good to go and create some basic code to manipulate MongoDB through Node.js.  This code is based on the commands from the following MongoDB wiki

Here are the steps for a basic CRUD (Create,Remove,Update & Delete) operations on MongoDB with Node.js

1. Create a folder c:\node\mongotest

2. Go to the directory where you have extracted the mongodb files and type in

mongod –dbpath c:\node\mongotest

This  will  start the database.

3. Here are the main functions of the code.

Connect to the mongodb database

var MongoClient = require('mongodb').MongoClient;
// Connect to the db
MongoClient.connect(“mongodb://localhost:27017/exampleDb”, function(err, db) {
if(!err) {
console.log(“We are connected”);
}

4. Create a collection of documents

//Create a collection test
console.log(“Creating a collection test”);
var collection = db.collection(‘test’);

5. Insert documents into the collection

//Create documents to insert
var doc1 = {‘hello’:’doc1′};
var doc2 = {‘hello’:’doc2′};
var lotsOfDocs = [{‘hello’:’doc3′}, {‘hello’:’doc4′}];
//Insert the docs
console.log(“Inserting the docs”);
collection.insert(doc1,function(err,result){});
collection.insert(doc2, {w:1}, function(err, result) {});

6. Update the inserted documents as follows

//Updating
var doc3 = {key:1,value:1};
collection.insert(doc3,{w:1},function(err,result) {
if(err) {
console.log(‘Could not insert’);
}
collection.update({key:1},{$set:{value:2}},{w:1},function(err,result) {});
});

7. Delete specific  documents from the database. Note: The remove() command requires a callback which I have included separately instead of the standard anonymous callback style

var mycallback = function(err,results) {
console.log(“mycallback”);
if(err) throw err;
}
//Deleting documents
console.log(“The delete operation”);
var doc4=[{key1:1},{key2:2},{key3:3}];
//Insert the document and then remove
collection.insert(doc4,{w:1},function(err,result) {
collection.remove({key1:1},mycallback);
collection.remove({key4:4},{w:1},mycallback);
});

8. Finally retrieve the inserted/updated records from the database

var stream = collection.find({mykey:{$ne:2}}).stream();
console.log(“Printing values…”);
stream.on(“data”, function(item) {
console.log(item);
});
stream.on(“end”, function() {});

The stream.on(“data”,) retrieves all the data till it encounters a stream.on(“end”).

So if I execute the above code I get the following output

C:\test \mongotest>node app3.js
We are connected
Creating a collection test
Inserting the docs
The delete operation
Printing values…
{ _id: 53c27ecbd5f4c59c1a2a5d39, hello: ‘doc1’ }
{ _id: 53c27ecbd5f4c59c1a2a5d3a, hello: ‘doc2’ }
{ _id: 53c27ecbd5f4c59c1a2a5d3b, key: 1, value: 1 }
{ _id: 53c27ecbd5f4c59c1a2a5d3c, key1: 1 }
{ _id: 53c27ecbd5f4c59c1a2a5d3d, key2: 2 }
{ _id: 53c27ecbd5f4c59c1a2a5d3e, key3: 3 }
mycallback
mycallback

The code can be cloned from Github at node-mongo

Also see
1. A Bluemix recipe with MongoDB and Node.js
2. Spicing up IBM Bluemix with MongoDB and NodeExpress
3. A Cloud Medley with IBM’s Bluemix, Cloudant and Node.js
4. Rock N’ Roll with Bluemix, Cloudant & NodeExpress


Find me on Google+

One thought on “Getting started with Node.js and Mongodb

Leave a comment