Integration of Node JS and MongoDB Simple Example

Filed Under: Node.js

In this post, we will discuss about how to integration Node JS Platform with MongoDB NoSQL Database and develop simple Node MongoDB Application.

Introduction to Node JS and MongoDB

We are already familiar with Node JS Platform. If you are new to Node JS, please go through my Node JS Basics posts.

MongoDB is Cross-Platform Document-Based, High Performance and Highly Scalable No SQL Data Store from MongoDB Inc. (formerly known as 10gen). It stores data in the form of Documents. To install and learn basics of MongoDB, please refer MongoDB Tutorial.

Node JS :MongoDB Setup

We should use “mongodb” Node JS module to develop Node JS Applications using MongoDB NoSQL Data Store. As this module is not a Default Node JS Module, we need to install this package using NPM (Node Package Manager).

To install “mondgodb” module:


 npm install -g mongodb

Here option “-g” means install this package globally and “mongodb” means install Node JS MongoDB module.

node-mongodb-install-output

Here ignore Errors. Those are related to some Windows OS and does not effect our Node JS Platform development.

Now Observe Node “mongodb” module in our local NPM Repository as shown below.

node-mongodb-install

Here we can observe new “mongodb” folder is added at “/node_modules” that means our installation is done successfully.

Node JS and MongoDB Example

Node JS and MongoDB setup is done. Now it’s time to develop a simple application to store data in MongoDB Store using Node JS Scripts. Like my previous examples, we use Enide Studio 2014 IDE to develop this application.

  • Create a Node JS Project in Enide IDE.
  • Project Name : “node-mongodb”

    NOTE:- Now on-wards, We will refer “PROJ_ROOT_DIR” value as follows

    ${PROJ_ROOT_DIR} = D:\RamWorkspaces\NodeWorkSpace\node-mongodb

  • Copy package.json file from my previous examples and updated it with the following content
  • package.json

    	
    {
      "name": "node-mongodb",
      "version": "1.0.0",
      "private": true,
      "scripts": {
        "start": "node node-mongodb.js"
      },
      "dependencies": {
    	"mongodb": "~2.0"
      }
    }
    

    NOTE:-

    1. As I have installed MongoDB 2.6 in my Windows 7 System, I’m refering “~2.0” value to Node: MongoDB Module. It should match to our mongodb module version.
    2. When I install “npm install -g mongodb”, it creates a “package.json” file at “node_modules/mongodb” folder
    3. In my system, it has created at “C:\Users\rambabu.posa\AppData\Roaming\npm\node_modules\mongodb” folder as shown below

      node-mongodb-package.json

      When we open this “package.json” file, you will find the following version for Node: MongoDB Module

      
       {
        "name": "mongodb",
        "version": "2.0.37",
        ...
       }
      

      That’s why we are using “mongodb” module version as “~2.0” in our project’s “package.json” file.

  • Add “mongodb” module library to our project.
  • Open command prompt at ${PROJ_ROOT_DIR}

    Install “npm install –save mongodb” command to

    Here option “–save” means pickup “mongodb” module library from our local NPM modules (C:\Users\rambabu.posa\AppData\Roaming\npm\node_modules) and add that library to our project.

    add-mongodb-library-project

    If we refresh our project in Enide IDE, we can observe that “mongodb” library was added to the project build path as shown below:

    node-mongodb-libs

  • Create a “node-mongodb.js” JavaScript file and update it the following content
  • node-mongodb.js

    
    var mongodb = require('mongodb');
    var mongoClient = mongodb.MongoClient;
    
    var url = 'mongodb://localhost:27017/jdproject';
    
    mongoClient.connect(url, function(err, db) {
          createDocuments(db, function() {
    	    db.close();
    	  });
    });
    
    var createDocuments = function(db, callback) {
         var collection = db.collection("jduser");
         collection.insert([
    	{firstname : "Rams",lastname: "Posa",emailid: "rams@journaldev.com"}, 
    	{firstname : "Mani",lastname: "Nulu",emailid: "mani@journaldev.com"},  
    	{firstname : "Bhargs",lastname: "Nulu",emailid: "Bhargs@journaldev.com"}, 
    	], function(err, result) {
    	callback(result);
          });
    }
    

    Code Explanation

    1. Line No: 1, Loaded our project dependency module “mongodb” into our project memory.
    2. Line No: 2, Using “mongodb” object created at Line No:1, we have create MongoDB Client.
    3. Line No: 4, It is a MongoDB Connection URL. It’s format is :
    4. 
       mongodb://[hostname]:[mongodb-server-port-number]/[mongodb-dbname]
      

      Example:-

      mongodb://localhost:27017/jdproject

      Here host is “localhost”
      MongoDB Default port number is “27017”
      My project MongoDB dbname is “jdproject”

    5. Line No: 6-10, Created MongoDB Connection using MongoDB Connection URL and making a call to “createDocuments” function.
    6. Line No: 12-21, Defined a “createDocuments” function.
    7. “createDocuments” function does the following things:

      Line No: 13, Creating a “jduser” MongoDB Collection.
      Line No: 14-20, Inserting 3 MongoDB Documents using “collection.insert()” function call into “jduser” MongoDB Collection.

  • Our final Project structure looks like this:
  • node-mongodb-proj-structure

  • Test our Node-MongoDB Application
  • Start MongoDB Server as shown below (My MongoDB is installed at “D:\MongoDB2.6”)

    
    mongod --config D:\MongoDB2.6\mongo.config
    

    start-mongodb-server

    Connect to MongoDB Client and check current DBs as shown below

    
    show dbs;
    

    mongodb-default-dbs

    Here we can observe only two default MongoDB Databases.

    Open CMD Prompt at ${PROJ_ROOT_DIR} and run our “node-mongodb.js” application as shown below

    
    node node-mongodb.js
    

    node-mongodb-proj-execute

    Now go to MongoDB Client and execute “show dbs” command and observe newly created “jdproject” db as shown below:

    mongodb-use-jdproject-db

    Connect to newly created “jdproject” MongoDB database, see newly created “jduser” MongoDB Collection & “jduser” Collection data as shown below

    
    use jdproject;
    show collections;
    db.jduser.find();
    

    mongodb-jduser-collection-data

That’s about Integration of Node JS Platform with MongoDB module and perform basic operation.

If you are not familiar with “How to install MongoDB software, how to configure it, how to start MongoDB server, how to connect to MongoDB Connection and Mongdb Commands”, please go through MongoDB Tutorial available in JournalDEV website.

We will discuss “How to perform CRUD operations on MongoDB Database” in my coming posts.

Please drop me a comment if you have any suggestions or issues.

Comments

  1. deepak rai says:

    Very nice tutorial keep it up man………..

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages