Connecting MongoDB and Node.js

We now have a solid understanding of the most basic concepts of how MongoDB works, and it is high time we put them to good work by integrating MongoDB with Node.js. In this section, we will cover this process step-by-step, and see how we can interact with the MongoDB databases directly from within a running Node.js instance.

Setting up a basic project

Before we start, please make sure that you have Node.js and Node Package Manager (NPM) installed on your system. Refer to Chapter 1, Setting Up Your Workspace, for the steps for your particular operating system.

Once you are set, start off by creating a basic project to experiment a bit with the MongoDB instance. Create a folder somewhere and call it MongoNode. Next, open a terminal (OS X/Linux) or the command prompt (Windows), navigate to this folder, and issue the following command:

npm init

This will launch an interactive wizard for the bootstrapping of a basic Node.js application. In the following code, we provide some standard answers to the questions that the wizard will ask:

name: (MongoNode)
version: (0.0.0)
description: Simple project demonstrating how to interface with a MongoDB instance from Node.js
entry point: (index.js)
test command:
git repository:
keywords:
author: Yours Truly
license: (BSD)
About to write to /home/user/IdeaProjects/nodebook-ch2/MongoNode/package.json:

{
  "name": "MongoNode",
  "version": "0.0.0",
  "description": "Simple project demonstrating how to interface with a MongoDB instance   from Node.js",
  "main": "index.js",
  "scripts": {
  "test": "echo "Error: no test specified" && exit 1"
  },
  "author": "Yours Truly",
  "license": "BSD"
}

Is this ok? (yes)

Once the bootstrapping finishes, create a new file named index.js. Open it in your favorite text editor and type the following:

console.log('Hello World!');

Save the file and then open a terminal. Navigate into the folder that we just created and run the following command:

node index.js

You should get the following familiar output:

Hello World!

We are now assured that Node.js works as expected. So, let's go ahead and see how we can get in touch with the database that we constructed earlier.

Connecting to MongoDB

Now, let's set up the bare metal to interface with a MongoDB instance. The first thing that we will need to do is install the official MongoDB driver for Node.js. Inside your project folder, issue the following command in the terminal:

npm install mongodb -save

This will make npm carry out the complete installation procedure. Once this is done, we will have all the basic functionalities that we need to interact with the MongoDB instance.

After the install finishes, create a new file named database.js, open it in your text editor, and insert the following. Don't worry if it is quite a lot of code as compared to what we have seen so far; I added quite a lot of commentary to explain what is going on:

// Our primary interface for the MongoDB instance
var MongoClient = require('mongodb').MongoClient;

// Used in order to verify correct return values
var assert = require('assert');

/**
*
* @param databaseName - name of the database we are connecting to
* @param callBack - callback to execute when connection finishes
*/
var connect = function (databaseName, callback) {

  // URL to the MongoDB instance we are connecting to
  var url = 'mongodb://localhost:27017/' + databaseName;

  // Connect to our MongoDB instance, retrieve the selected
  // database, and execute a callback on it.
  MongoClient.connect(url, function (error, database) {

    // Make sure that no error was thrown
    assert.equal(null, error);

    console.log("Successfully connected to MongoDB instance!");

    callback(database);
  });
};

/**
* Executes the find() method of the target collection in the
* target database, optionally with a query.
* @param databaseName - name of the database
* @param collectionName - name of the collection
* @param query - optional query parameters for find()
*/
exports.find = function (databaseName, collectionName, query) {
  connect(databaseName, function (database) {

    // The collection we want to find documents from
    var collection = database.collection(collectionName);

    // Search the given collection in the given database for
    // all documents which match the criteria, convert them to
    // an array, and finally execute a callback on them.
    collection.find(query).toArray(
      // Callback method
      function (err, documents) {

        // Make sure nothing went wrong
        assert.equal(err, null);

        // Print all the documents that we found, if any
        console.log("MongoDB returned the following documents:");
        console.dir(documents);

        // Close the database connection to free resources
        database.close();
    })
  })
};

Next, let's import the database module in the index.js file. Remove everything from this file and insert the following in it:

var database = require('./database');

This will allow us to use our database interface like a regular Node.js module.

Finally, let's give it a run and make sure that everything works. Insert the following line in the index.js file:

database.find('OrderBase', 'Products', {});

The preceding command should immediately seem familiar to you; it is the same as when we ran the following command in our earlier example:

db.Products.find();

Here, we simply wrapped the parameters in logic so that it can be run in the Node.js instance.

To run the Node.js instance, issue the following command in your terminal again:

node index.js

You should receive something like the following:

Successfully connected to MongoDB instance!

MongoDB returned the following documents:

[ { _id: 54f8f04a598e782be72d6294, name: 'Apple', price: 2.5 },
  { _id: 54f8f6b8598e782be72d6295, name: 'Pear', price: 1.5 },
  { _id: 54f8f6b8598e782be72d6296, name: 'Orange', price: 3 },
  { _id: 54f9b82caf8e5041d9e0af09, name: 'Banana', price: 3 } ]
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.140.197.10