Resilient connections between Node.js and MongoDB in Bluemix

5 min read

By: LUKE MCKENNA

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.

logo

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 mongoosejs.com 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):

    <br>
    // for your local testing<br>
    dbURI = 'mongodb://127.0.0.1:27017/' + '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>
      }<br>
    }<br>
    </p>
  4. Now for the resilient connection:

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

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 compose.io, 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. The timeout suggestion for MongoDB in PaaS environments came from the MongoLab blog entry Do you want a timeout?

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