Resilient connections between Node.js and MongoDB in Bluemix

1 min read

Resilient connections between Node.js and MongoDB in Bluemix

Republished from Bluemix – Real use cases Updated to add sample code and instructions for using MongoDB by Compose service. Updated to remove mention of MongoLab as it’s no longer an available service in Bluemix.


If you’re reading this, you’ve probably got your Node.js app connecting to MongoDB somehow – maybe even using Mongoose. What happens if the connection between Node.js and MongoDB is severed for any reason? You will want your app to reconnect under all circumstances. You also need to know how to get your MongoDB credentials for connection at runtime in Bluemix.

Here’s how to do it all in just 4 steps:

  1. Ensure you are using the MongoDB by Compose service on Bluemix. To use the Compose service first sign up for a Compose account (free for 30 days), then log into your Compose account and create a new MongoDB database – note down the name of your database.

  2. If you’re not using Mongoose and want to, start with and make sure you have done this:

    $ npm install [--save] mongoose

    and added this to your application:

    mongoose = require('mongoose');
  3. Create the dbURI with credentials at runtime for your Compose service (you'll need to have created and bound your service for MongoDB by Compose):

    // for your local testing<br>
    dbURI = 'mongodb://' + 'test'; <p></p>
    <p>// for MongoDB by Compose service<br>
    if (process.env.VCAP_SERVICES) {<br>
      var env = JSON.parse(process.env.VCAP_SERVICES);</p>
    <p>  if (env['user-provided']) { // for Compose<br>
          var cm = env['user-provided'][0].credentials;<br>
          var dbname = 'mymongodb'; // you noted this earlier<br>
          dbURI = 'mongodb://'<br>
              + cm.user<br>
              + ':' + cm.password<br>
              + '@' + cm.uri<br>
              + ':' + cm.port<br>
              + '/' + dbname;<br>
  4. Now for the resilient connection:

    var db = mongoose.connection;<br>
    db.on('connecting', function() {<br>
    <p>db.on('error', function(error) {<br>
        console.error('Error in MongoDb connection: ' + error);<br>
    db.on('connected', function() {<br>
    db.once('open', function() {<br>
        console.log('connection open');<br>
    db.on('reconnected', function () {<br>
    db.on('disconnected', function() {<br>
        console.log('dbURI is: '+dbURI);<br>
          {server: {auto_reconnect:true,<br>
          socketOptions: { keepAlive: 1, connectTimeoutMS: 30000 }},<br>
          replset: { socketOptions: { keepAlive: 1, connectTimeoutMS : 30000 } }});<br>
    console.log('dbURI is: '+dbURI);<br>
    mongoose.connect(dbURI, {server:{auto_reconnect:true}});<br>

Some personal opinions about the MongoDB by Compose service:

  • The MongoDB by Compose service currently requires you to sign up for an account first at, which is all pretty straight forward.

  • The MongoDB by Compose VCAP_SERVICES doesn’t contain the database name, but is easily remedied either in code or (preferably) by using a custom environment variable.

  • The MongoDB can be accessed externally by simply using the username/password credentials which is great for doing direct updates to the DB.

Credits: This style of resilient connection code was mentioned a number of times on Stack Overflow, but this post was the most straight forward: Mongoose autoReconnect option.

PS: Given the authentication changes in MongoDB v3.0+, be sure you are using recent versions of the MongoDB driver or Mongoose. You may find some MongoDB services now require SCRAM-SHA-1 authentication.

Be the first to hear about news, product updates, and innovation from IBM Cloud