Node.js with MongoDB


The MongoDB Node.js driver is the officially supported node.js driver for MongoDB. In Spring 2012, MongoDB officially adopted the popular Node MongoDB Native Project and sponsored the maintainer, Christian Kvalheim, to continue its development. It is written in pure JavaScript and provides a native asynchronous Node.js interface to MongoDB. The driver is optimized for simplicity. It can be used on its own, but it also serves as the basis of several object mapping libraries, such as Mongoose.

Install or Upgrade

The easiest way to install is to use npm

npm install mongodb

MongoDB Compatibility

The following compatibility table specifies the recommended version(s) of the MongoDB Node.js driver for use with a specific version of MongoDB.

The first column lists the driver version(s).

Node.js Driver MongoDB 2.4 MongoDB 2.6 MongoDB 3.0 MongoDB 3.2
>=2.1.0 YES YES YES YES
>=2.0.14 YES YES YES  

Declare MongoClient variable

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.

MongoDB server startup

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.

Object Mappers

Because MongoDB is so easy to use, the basic Node.js driver can be the best solution for many applications. However, if you need validations, associations, and other high-level data modeling functions, then an Object Document Mapper may be helpful.

Mongoose

Mongoose is an ODM for Node.js. It has a thriving open source community and includes advanced schema-based features such as async validation, casting, object life-cycle management, pseudo-joins, and rich query builder support.

Install it easily with npm:

npm install mongoose

Connecting to MongoDB

First, we need to define a connection. If your app uses only one database, you should use mongoose.connect. If you need to create additional connections, use mongoose.createConnection.

Both connect and createConnection take a mongodb:// URI, or the parameters host, database, port, options.

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/database');

Note: Mongoose buffers all the commands until it's connected to the database. This means that you don't have to wait until it connects to MongoDB in order to define models, run queries, etc.

Defining a Model

Models are defined through the Schema interface.

var Schema = mongoose.Schema,
    ObjectId = Schema.ObjectId;
 
var BlogPost = new Schema({
    author    : ObjectId,
    title     : String,
    body      : String,
    date      : Date
});

Aside from defining the structure of your documents and the types of data you're storing, a Schema handles the definition of:

Accessing a Model

Once we define a model through mongoose.model('ModelName', mySchema), we can access it through the same function

var myModel = mongoose.model('ModelName');

The first argument is the singular name of the collection your model is for. Mongoose automatically looks for the plural version of your model name.

var MyModel = mongoose.model('Ticket', mySchema);

Then Mongoose will create the model for your tickets collection, not your ticket collection.