a blog for those who code

Friday, 25 July 2014

Use MongoDB in Nodejs

In this post we will learn how to use MongoDB in Nodejs. As you all know that MongoDB is a NoSQL type of database and in future it will be in a good demand. So why not start early, lets start of using MongoDB with Nodejs.

So at first you should know that how MongoDB stores data. MongoDB stores structured data as documents rather than implementing the more traditional tables like in SQL Server and all. These documents are encoded as binary form of JSON(also called as BSON) i.e. instead of table row we have BSON document.

At first, we have to require the MongoDB module.

var mongodb = require('mongodb');

Then we have to establish a connection to MongoDB.

var connection = new mongodb.Server('localhost',:27017, {auto_reconnect : true});

Note that all communication with the MongoDB database occur over TCP. The server constructor accepts the host and port as the first two parameters. The third parameter is as set of options, auto_reconnect is set to true which means if the connection is lost, driver will attempt to re-establish a connection. Another option which is not stated above is poolSize, which determines how many TCP connections are maintained in parallel. So you can specify poolSize when creating a connection as how many TCP connections you required.

Note that MongoDB uses one thread per connection, because of that I will recommended you to use connection pooling. Now once you have connected to MongoDB, you can either create a database or connect to an existing database using the below command.

var db = new mongodb.Db('db_name', connection);

In this above example first parameter is the database name and the second is the MongoDB server connection. Just note that MongoDB runs without authentication. You dont have to provide username and password for authentication, that's why its recommended to run MongoDB in a trusted environment.

In my next post I will show you how to use collections in MongoDB. Please Like and Share the Blog, if you find it interesting and helpful.

No comments:

Post a Comment

Contact Us

Name

Email *

Message *

Sponsers

Best Hosting Plans

CC License