Node.js Driver

MongoDB Node.js Driver is the officially supported Node.js driver for MongoDB.

Procedure

1

Install Node.js and npm

OS X/Windows

Download the installer from http://nodejs.org/download/ and run to install Node.js and npm.

Other supported platforms

Download the Node.js and npm binaries from http://nodejs.org/download/.

Ensure the installed Node.js and npm are in the appropriate path.

2

Install MongoDB Node.js Driver

Use npm to install the MongoDB Node.js driver.

npm install mongodb
3

Declare MongoClient variable and other variables.

Complete the remainder of this procedure in a node interactive shell or other environment (e.g. script).

var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');

Connect using the MongoClient to a running mongod instance by specifying the MongoDB uri. For example, the following code connects to a MongoDB instance that runs on the localhost interface on port 27017 and switch to the test database.

var url = 'mongodb://localhost:27017/test';
MongoClient.connect(url, function(err, db) {
  assert.equal(null, err);
  console.log("Connected correctly to server.");
  db.close();
});

A successful connection should print out the following line:

Connected correctly to server.

Otherwise, the code throws an assertion.

Additional Information

For more information on installation, see http://mongodb.github.io/node-mongodb-native/2.0/overview/installing/