Skip to content

Commit 6ae34da

Browse files
author
Martii
committed
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 OpenUserJS#845, OpenUserJS#851, Automattic/mongoose#3588 and loosely christkv/mongodb-core#66
1 parent 1588b40 commit 6ae34da

File tree

1 file changed

+25
-1
lines changed

1 file changed

+25
-1
lines changed

app.js

+25-1
Original file line numberDiff line numberDiff line change
@@ -86,14 +86,38 @@ app.set('securePort', process.env.SECURE_PORT || null);
8686

8787
// Connect to the database
8888
mongoose.connect(connectStr, dbOptions);
89-
db.on('error', console.error.bind(console, 'connection error:'));
89+
90+
// Trap a few events for MongoDB
91+
db.on('error', function () {
92+
console.error(chalk.red('MongoDB connection error'));
93+
});
94+
9095
db.once('open', function () {
96+
console.log(chalk.green('MongoDB connection is opened'));
97+
});
98+
99+
db.on('connected', function () {
91100
var admin = new mongoose.mongo.Admin(mongoose.connection.db);
92101
admin.buildInfo(function (aErr, aInfo) {
93102
console.log(chalk.green('Connected to MongoDB v' + aInfo.version));
94103
});
95104
});
96105

106+
db.on('disconnected', function () {
107+
console.error(chalk.yellow('\nMongoDB connection is disconnected'));
108+
});
109+
110+
db.on('reconnected', function () {
111+
console.error(chalk.yellow('MongoDB connection is reconnected'));
112+
});
113+
114+
process.on('SIGINT', function () {
115+
db.close(function () {
116+
console.log(chalk.green('MongoDB connection disconnected gracefully with app termination'));
117+
process.exit(0);
118+
});
119+
});
120+
97121
var sessionStore = new MongoStore({ mongooseConnection: db });
98122

99123
// Force HTTPS

0 commit comments

Comments
 (0)