title: Nodejs: wait for mongodb connection to be made, before creating http server
body: <p>in my <code>app.js</code>, I create a mongodb connection when app starts.</p>
  
  <pre><code>mongoose.connect(config.db, {});
  
  var db = mongoose.connection;
  db.on('error', function () {
      log.error("Failed to connect to database");
      process.exit(1);
  });
  db.once('open', function () {
      log.info("Connected to database");
  });
  </code></pre>
  
  <p>The <code>app.js</code> is used from <code>bin/www.js</code> (with <code>require('./../app')</code>), in which the http server is created.</p>
  
  <p>Currently, if db connection is unsuccessful, app terminates, but http server got created before terminating, since db creation failure is reported asynchronously.</p>
  
  <p>I need to block http server creation until db connection is successful, but I need to keep the server creation code in <code>bin/www.js</code> itself, without moving it to db connection successful callback in <code>app.js</code>.</p>
  
  <p>Is there any way I can do this?</p>