title: How to properly end a MongoDB client connection on error?
body: <p>I have a MongoDB instance and two JavaScript services running on a Linux server. The first service, moscaService.js, listens to MQTT topics on the server, and records what is sent in a MongoDB collection. The second service, integrationService.js, runs every second, reading data on the same MongoDB collection and, if there's a new register (or more), sends it to Ubidots.</p>
  
  <p>The problem is that both services work on the same IP/port: localhost:27017; and, if there ever is an occasion in which both of them are active simultaneously (say, moscaService.js is recording something and then the integrationService.js tries to connect), there will be a connection error and the service will restart.</p>
  
  <p>Here are the connection parts of both services:</p>
  
  <pre><code>var MongoClient = require('mongodb').MongoClient;
  var url = 'mongodb://127.0.0.1:27017/myGateway';
  
  
  //integrationService.js
  var job1 = new CronJob('*/1 * * * * *', function() {
    MongoClient.connect(url, function(err, db) {
        if(err != null) {
            logger.error({message: 'Connection error: ' + err});
            process.exit(0);
        } else {
            executeService();
        }
  
        function executeService() {
          // execution block
        }
    });
  }, null, true, timeZone);
  
  
  //moscaService.js
  server.on('published', function(packet, client) {
  
    //the packet is read here
  
    MongoClient.connect(url, function(err, db) {
        if(err != null) {
            logger.error({message: 'Connection error: ' + err});
            process.exit(0);
        } else {
            executeService();
        }
  
        function executeService() {
          // execution block
        }
    });
  });
  </code></pre>
  
  <p>What I need is a way to properly handle the <code>err</code> instead of just exiting the service, because if there are new messages being published while the service is restarting, they will be lost. Something like testing if the port is open before connecting, or open a different port.</p>
  
  <p>I tried creating another instance of MongoDB on a different port, in order to have each service listen to one, but it looks like Mongo locks more than one instance if it's trying to connect to the same database.</p>
  
  <p>The code snippets here are just a small part; if anyone needs more parts to answer, just say so and I'll add them.</p>