AppFog and MongoDB 2 Configuration

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.

Like This?

If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support. You can also subscribe to the email feed to get notified of new posts.