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?
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()
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With