Sunday, April 6, 2014

Connecting To MongoDB From Node.js Beginner's Basic

Ok guys - Here we will create a simple file that will connect to a local instance of Mongo and read data from the 'test' database.

Assumptions - 
1 - A local Mongo server is running at port 27017 (default port)

Step 0 - Create a directory called 'testing' and cd into it.

Step 1 - Connect to mongo using a mongo shell
Step 2 -  Add some data to a collection named 'heroes' in the test db.
              use test
             db.heroes.insert([{name: 'Super Man'}, {name: 'Bat Man'}]) 

Step 3 - Create a file called simple_connect.js and the following content to the file

             
var MongoClient = require('mongodb').MongoClient;
var connectionString = 'mongodb://localhost:27017/test';
// connect to test db
MongoClient.connect(connectionString, function(err, db) {
if(err) throw err;
console.log("CONNECTED");
var q = {name: 'Super Man'};
// query superheroes collection and display result
db.collection('heroes').findOne(q,function(err, doc) {
if(err) throw err;
console.dir(doc);
db.close();
});
});

Step 4 - If you haven't already installed the 'mongodb' module, run
             npm install mongodb

Step 4 - Run
             node simple_connect.js