Skip to content

Commit

Permalink
Add some event traps for MongoDB
Browse files Browse the repository at this point in the history
* Gracefully disconnect from MongoDB during restarts
* Add some console messages in for tracking
* Remove the `bind` on error trap

Applies to OpenUserJS#845, OpenUserJS#851, Automattic/mongoose#3588 and loosely christkv/mongodb-core#66
  • Loading branch information
Martii committed Dec 16, 2015
1 parent 1588b40 commit 6ae34da
Showing 1 changed file with 25 additions and 1 deletion.
26 changes: 25 additions & 1 deletion app.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 6ae34da

Please sign in to comment.