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

             

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

Step 4 - Run
             node simple_connect.js