Connecting to MongoDB from Node.js using MongoDB driver

Posted by: Ravi Kiran , on 8/1/2015, in Category Node.js
Views: 19253
Abstract: Using Node.js to connect to a MongoDB database using MongoDB Drivers

Node.js is a platform that makes it possible to write server side code using JavaScript. As JavaScript is a type less language, it plays well with the NOSQL databases. One of the prominent NOSQL databases is MongoDB. It gained a lot of popularity because it is easy to install and to use. One more reason why databases like MongoDB are obvious choice with Node.js is because the database takes and produces JSON data. So, in Node.js applications, we need not worry about serializing and de-serializing data while working with MongoDB.

Note: If you are new to Node.js, please go through these articles to get a good understanding of Node.

Node.js Tutorial Series - Getting Started

Node.js Serving HTML pages and Static content

Using Node.js to build REST APIs

Node.js Module System

Understanding NPM

To interact with any database from any platform, we need a driver that makes the interaction possible. Similarly, to interact with MongoDB from Node.js, we need a driver. We have several drivers available for this purpose. MongoDB driver is one of them.

The MongoDB driver provides just enough abstraction to connect to and interact with MongoDB. It doesn’t hide the way we query collections in MongoDB. We can use the same queries that are used in MongoDB console with the MongoDB driver as well.

Installing and Referring MongoDB

The MongoDB driver is an NPM package. It can be installed using the following NPM command:

> npm install mongodb

To use it in a Node.js file, we need to load the module using the require function.

var mongoDb=require('mongodb');

As I have been mentioning since first article in this series, Node.js treats all I/O and network operations asynchronously. As interacting with a MongoDB database is similar to interacting with a file on the system, these operations are also executed asynchronously.

Connecting to MongoDB

To connect to a MongoDB database, you need to have MongoDB installed and the service running in the background. Once you have the database service running, you can establish a connection to it using the MongoClient object of the mongodb object created above. Following snippet connects MongoDB with Node.js:

var mongoClient=require('mongodb').MongoClient;
var mongoDbObj;
mongoClient.connect('mongodb://localhost/testDb', function(err, db) {
  if (err)
    console.log(err);
  else {
    console.log("Connected to MongoDB");
    mongoDbObj = {
      db: db,
      todoList: db.collection('todos')
    };
  }
});

Here, we are trying to connect to the database testDb. If the database exists, the connection will be established directly. Otherwise, the database will be created and the connection will then be established. Similarly, the collection todos will be created on the fly, if it doesn’t already exist. As MongoDB doesn’t impose schemas on the collections, data of any format can be stored inside the collection todos.

The todoList property is created inside the object mongoDbObj to have a handy reference to the collection. We will be dealing with this property to perform CRUD operations on the collection todos.

Performing CRUD Operations

The API of the MongoDB driver is similar to the way we query the database from command prompt. As we just created the database, let’s insert some data into it. Following statement adds a few rows into the todos collection:

mongoDbObj.todoList.insert([{
  id:1,
  title:"Toast Bread",
  done:false
},
{
  id:2,
  title:"Prepare tea",
  done:false
}], {w:1}, function (err, res) {
   if(err){
     //Handle error
   }
   else{
     //Use the result
   }}
);

The second value sent to the method ({w:1}) is an options object. The value passed indicates that we need an acknowledgement of the insert option.

The same API can be used to insert a single object as well. In this case, we will pass a single object instead of passing an array.

We can fetch the entries in a collection using the find method. The same method can be used with different parameters to fetch all entries or, a filtered set of entries based on a condition. The function returns a cursor that lazily loads data upon calling toArray, each or, nextObject methods on it. Following are some examples of using find:

mongoDbObj.todos.find().toArray(function(err, data){
  if(err){
    //Handle error
  }
  else{
    //Use result
  }
});  //Fetches all todos
mongoDbObj.todos.find({id:1});  //Fetches the todo item with id 1
mongoDbObj.todos.find({id:{$lte: 3}});  //Fetches the todo items with id less than or equal to 3

To update entries in a database, we need to use the update method. The update method either replaces the entire entry or, patches the changes to the entry based on a parameter sent to it. Following snippet shows both these cases:

mongoDbObj.todoList.update({id: 1},{ id: 1, title: "Something..."}, {w:1}, function (error, result) {
  if(err){
    //Handle error
  }
  else{
    //Use result
  }
});

mongoDbObj.todoList.update({id: 2},{"$set":updatedTodo}, {w:1}, function (error, result) {
  if(err){
    //Handle error
  }
  else{
    //Use result
  }
});

Similarly, the entries can be removed using the remove method. If it is called without any parameters, it removes all the entries. Otherwise, it removes the entries that match the condition.

mongoDbObj.students.remove(function(err, result){  //Removes all entries in the collection
  if(err){
    //Handle error
  }
  else{
    //Use result
  }
});
mongoDbObj.students.remove({id: 1},{w: 1}function(err, result){  //Removes entries with id=1
  if(err){
    //Handle error
  }
  else{
    //Use result
  }
});

Conclusion

MongoDB and Node.js play pretty well together. They are used along with Express.js and AngularJS (otherwise called MEAN stack) to build end-to-end applications using just one programming language. Also, as MongoDB (like other NOSQL DBs) is a schema-less database, the object model of both ends fit well together. We will see more examples of using Node and MongoDB in future articles.

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce the The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this eBook aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on .NET Standard and the upcoming C# 8.0 too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Rabi Kiran (a.k.a. Ravi Kiran) is a developer working on Microsoft Technologies at Hyderabad. These days, he is spending his time on JavaScript frameworks like AngularJS, latest updates to JavaScript in ES6 and ES7, Web Components, Node.js and also on several Microsoft technologies including ASP.NET 5, SignalR and C#. He is an active blogger, an author at SitePoint and at DotNetCurry. He is rewarded with Microsoft MVP (Visual Studio and Dev Tools) and DZone MVB awards for his contribution to the community


Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!

Categories

JOIN OUR COMMUNITY

POPULAR ARTICLES

C# .NET BOOK

C# Book for Building Concepts and Interviews

Tags

JQUERY COOKBOOK

jQuery CookBook