From 6ae34da2c0ab07293203296cd82b7fe4248bcd9b Mon Sep 17 00:00:00 2001 From: Martii Date: Wed, 16 Dec 2015 13:18:33 -0700 Subject: [PATCH] Add some event traps for MongoDB * Gracefully disconnect from MongoDB during restarts * Add some console messages in for tracking * Remove the `bind` on error trap Applies to #845, #851, Automattic/mongoose#3588 and loosely christkv/mongodb-core#66 --- app.js | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/app.js b/app.js index 53a0706b9..ec9c6cdd2 100755 --- a/app.js +++ b/app.js @@ -86,14 +86,38 @@ app.set('securePort', process.env.SECURE_PORT || null); // Connect to the database mongoose.connect(connectStr, dbOptions); -db.on('error', console.error.bind(console, 'connection error:')); + +// Trap a few events for MongoDB +db.on('error', function () { + console.error(chalk.red('MongoDB connection error')); +}); + db.once('open', function () { + console.log(chalk.green('MongoDB connection is opened')); +}); + +db.on('connected', function () { var admin = new mongoose.mongo.Admin(mongoose.connection.db); admin.buildInfo(function (aErr, aInfo) { console.log(chalk.green('Connected to MongoDB v' + aInfo.version)); }); }); +db.on('disconnected', function () { + console.error(chalk.yellow('\nMongoDB connection is disconnected')); +}); + +db.on('reconnected', function () { + console.error(chalk.yellow('MongoDB connection is reconnected')); +}); + +process.on('SIGINT', function () { + db.close(function () { + console.log(chalk.green('MongoDB connection disconnected gracefully with app termination')); + process.exit(0); + }); +}); + var sessionStore = new MongoStore({ mongooseConnection: db }); // Force HTTPS