AppFog and MongoDB 2 Configuration

This post is more than 2 years old.

Just a quick tip. I'm using AppFog for my Node.js version of and ran into an issue with their MongoDB2 support. When you use AppFog services, they document how your code can dynamically read configuration information from their server. This is required since things like MongoDB support are configured uniquely per deployed application.

The documentation demonstrates how to do this in various languages. Here is the code sample for Node.js:

    var env = JSON.parse(process.env.VCAP_SERVICES);
    var mongo = env['mongodb-1.8'][0]['credentials'];
    var mongo = {

var generate_mongo_url = function(obj){
    obj.hostname = (obj.hostname || 'localhost');
    obj.port = (obj.port || 27017);
    obj.db = (obj.db || 'test');

    if(obj.username && obj.password){
        return "mongodb://" + obj.username + ":" + obj.password + "@" + obj.hostname + ":" + obj.port + "/" + obj.db;
        return "mongodb://" + obj.hostname + ":" + obj.port + "/" + obj.db;

var mongourl = generate_mongo_url(mongo);

Simple, right? Except that AppFog offers both MongoDB 1.8 and 2.4.8. If you use 2.4.8, you must change the line reading credentials too:

var mongo = env['mongodb2-2.4.8'][0]['credentials'];

The error is pretty obvious when deploying from the CLI, but I wasn't sure of the exact change until I console.logged the JSON variable and viewed my log.

Raymond Camden's Picture

About Raymond Camden

Raymond is a developer advocate for HERE Technologies. He focuses on JavaScript, serverless and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support. You can even buy me a coffee!

Lafayette, LA