Getting Started with MongoDB on Node.js on OpenShift - Archived

Node and MongoDB are a killer combination, providing powerful tools for quickly managing, storing, and querying collections of extensible JSON data objects. No data tranformation or SQL translations required.

To get started with MongoDB on Node.js, try spinning up a new application instance from the command line, listing nodejs and mongodb-2.2 as your cartridge service dependencies:

rhc app create YOUR_APP_NAME nodejs mongodb-2.2

After your application gear is created, the cartridge-based services will be installed and configured automatically. A fresh set of randomly-generated authentication credentials will be returned to you in the output. This information will be made available to your applications via environment variables as well, so you won’t need to write it down or include any of it in your source code.

After the process is complete, step into your application’s source code folder to provide a default application name for most of the subsequent rhc commands in this guide:


For existing node-based OpenShift applications, MongoDB support can be easily added:

rhc cartridge add mongodb-2.2

If you would like a web front-end for interacting with your MongoDB instance, the RockMongo MongoDB administration cartridge can also be added to your applicaiton in a single step:

rhc cartridge add rockmongo

An easy web-based workflow for adding functionality via cartridges is also available, just click on the “add cartridge” link while visiting your application in the OpenShift web management console (

Loading up the mongo interactive shell

First, connect to your application gear via ssh:

rhc ssh

Then type mongo to enter the interactive command-line interface.

While we’re connected, lets add some data for us to query. Since MongoDB allows for unstructured, “NoSQL” data, we’ll be storing our records in documents instead of structured rows, and in collections instead of tables. For simplicity, lets reuse our APP_NAME as the database name.

// select your database
// insert a book record into a collection of "books"
db.books.insert({ title:'MongoDB in the Wild', description: "Tales of NoSQL Adventures"})

Connecting to the database from Node

Typing rhc app show is a handy way to find your MongoDB and RockMongo account login information. These variables will also be made available in your application’s system environment while running on OpenShift.

The two most important environment variables for your application source, are the internal IP address and port number that your server will need to attach to, in order to accept external connections.

The following conditional assignment operation allows you to write code that will work in local development, while providing automatic support for OpenShift whenever the appropriate environment variables are available:

var ip_addr = process.env.OPENSHIFT_NODEJS_IP   || '';
var port    = process.env.OPENSHIFT_NODEJS_PORT || '8080';

We can do something similar for the MongoDB connection string:

// default to a 'localhost' configuration:
var connection_string = '';
// if OPENSHIFT env variables are present, use the available connection info:
  connection_string = process.env.OPENSHIFT_MONGODB_DB_USERNAME + ":" +
  process.env.OPENSHIFT_MONGODB_DB_HOST + ':' +
  process.env.OPENSHIFT_MONGODB_DB_PORT + '/' +

Port Forwarding

If you do not have a local instance of MongoDB in your development environment, or if you would like to use the same data set in your OpenShift hosting environment as in your development environment, establishing an ssh tunnel can help make provide a local interface to the remote DB:

rhc port-forward APP_NAME

While the tunnel is open, run mongo from another terminal to test connecting via the command line. To close the tunnel, press CTRL-C.

Mongojs vs node-mongodb-native

My two favorite npm modules for working with MongoDB are node-mongodb-native and mongojs. I’ll provide a quick overview of each.


This is the library that you’ll get when you type npm install mongodb. It’s the most popular MongoDB interface, it’s written entirely in javascript, and it’s recommended by the 10gen team.

The node-mongodb-native github repository includes a well-documented README file, with links to additional docs.

To initialize the module, run npm install mongodb, and run the following code in order to request ten documents from the books collection:

//load the Client interface
var MongoClient = require('mongodb').MongoClient;
// the client db connection scope is wrapped in a callback:
MongoClient.connect('mongodb://'+connection_string, function(err, db) {
  if(err) throw err;
  var collection = db.collection('books').find().limit(10).toArray(function(err, docs) {

Unfortunately, this nested db interaction style may help contribute to callback hell if not managed carefully.

The 10gen team puts a lot of effort into making the MongoDB client interface feel like a native experience in each language. This one is very nice, but I think the one offered by Mongojs feels a little more natural.


Mongojs is also available on GitHub. It can be installed with:

npm install mongojs

I think that this interface feels more true to the actual javascript-style mongo interactive shell:

var mongojs = require('mongojs');
var db = mongojs(connection_string, ['books']);
var books = db.collection('books');
// similar syntax as the Mongo command-line interface
// log each of the first ten docs in the collection
db.books.find({}).limit(10).forEach(function(err, doc) {
  if (err) throw err;
  if (doc) { console.dir(doc); }

The db reference does not need to be wrapped in a Client.connect callback, which makes this code feel much cleaner to me.

The MongoDB Manual, includes much more information on the commands and queries supported by the MongoDB interface shell. For additional information on the Mongojs, and node-mongodb-native modules, try their respective github pages.

Happy Hacking!

What’s Next?

MongoDB, News, Node.js, OpenShift Online, OpenShift Origin
Comments are closed.