title: Check if mongoDB is connected
body: <p>I have mongoDB in my app.</p>
  
  <p>I want to check if mongoDB is connected, before I listen to the app.</p>
  
  <p>Is it the best way for doing it?</p>
  
  <p>This is my server.js file:</p>
  
  <pre><code>var express = require('express');
  var mongoDb = require('./mongoDb');
  var app = express();
  
  init();
  
  function init() {
      if (mongoDb.isConnected()) {
        app.listen(8080, '127.0.0.1');
      }
      else {
        console.log('error');
      }
  }
  </code></pre>
  
  <p><code>isConnected</code> runs <code>getDbObject</code>. 
  <code>getDbObject</code> connects to mongoDB and returns an object:
   connected (true/false), db (dbObject or error).</p>
  
  <p>Then, <code>isConnected</code> resolve/reject by connected property.</p>
  
  <p>This is mongoDb.js file:</p>
  
  <pre><code>//lets require/import the mongodb native drivers.
  var mongodb = require('mongodb');
  // Connection URL. This is where your mongodb server is running.
  var url = 'mongodb://localhost:27017/myDb';
  
  var connectingDb; // promise
  
  //We need to work with "MongoClient" interface in order to connect to a mongodb server.
  var MongoClient = mongodb.MongoClient;
  
  init();
  
  module.exports = {
      isConnected: isConnected
  }
  
  // Use connect method to connect to the Server
  function init() {
    connectingDb = new Promise(
      function (resolve, reject) {
        MongoClient.connect(url, function (err, db) {
          if (err) {
            console.log('Unable to connect to the mongoDB server. Error:', err);
            reject(err);
          }
          else {
            console.log('Connection established to', url);
  
            //Close connection
            //db.close();
            resolve(db);
          }
        });
  
      }
    );
  }
  
  function getDbObject() {
    return connectingDb().then(myDb =&gt; {
                                         return {
                                            connected: true,
                                            db: myDb
                                          }
                                        }
                                )
                         .catch(err =&gt;  {
                                          return {
                                            connected: false,
                                            db: err
                                          }
                                        }
                               )
  }
  
  function isConnected() {
      return new Promise(
          function(resolve, reject) {
            var obj = getDbObject();
            if (obj.connected == true) {
              console.log('success');
              resolve(true);
            }
            else {
              console.log('error');
              reject(false);
            }
          }
      )
  
  }
  </code></pre>
  
  <p>Any help appreciated!</p>