Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs: wait for mongodb connection to be made, before creating http server

in my app.js, I create a mongodb connection when app starts.

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");
});

The app.js is used from bin/www.js (with require('./../app')), in which the http server is created.

Currently, if db connection is unsuccessful, app terminates, but http server got created before terminating, since db creation failure is reported asynchronously.

I need to block http server creation until db connection is successful, but I need to keep the server creation code in bin/www.js itself, without moving it to db connection successful callback in app.js.

Is there any way I can do this?

like image 970
Lahiru Chandima Avatar asked Feb 12 '17 10:02

Lahiru Chandima


1 Answers

You can launch your server only when the connection is done:

db.once('open', function () {
   log.info('Connected to database');
   launchMyServer()
});

or if you want to use it in another file :

module.exports = function initConnection(callback) {
  mongoose.connect(config.db, {});
  var db = mongoose.connection;
  db.on('error', function (err) {
    log.error('Failed to connect to database');
    process.exit(1);
  });

  db.once('open', function () {
    log.info("Connected to database");
    callback();
  });
};

And from your www.js file:

const initConnection = require('./../app')

initConnection(function () {
  launchMyServer()
})
like image 163
L. Meyer Avatar answered Oct 21 '22 07:10

L. Meyer