Skip to content

Instantly share code, notes, and snippets.

@jkrenge
Created October 20, 2015 16:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jkrenge/79d25ace8ce3bb0a0986 to your computer and use it in GitHub Desktop.
Save jkrenge/79d25ace8ce3bb0a0986 to your computer and use it in GitHub Desktop.
Handling a persistent MongoDB connection with mongoose from a Express.js server in Node.js
mongoose.connection.on("error", function(err) {
console.error('> Failed to connect to MongoDB on startup ', err);
});
mongoose.connection.on('disconnected', function() {
console.log('> Mongoose default connection to MongoDB disconnected');
});
var gracefulExit = function() {
mongoose.connection.close(function() {
console.log('> Mongoose default connection with MongoDB is disconnected through app termination');
process.exit(0);
});
};
process.on('SIGINT', gracefulExit).on('SIGTERM', gracefulExit);
try {
mongoose.connect(settings.mongodb.path, settings.mongodb.options);
console.log('> Trying to connect to MongoDB...');
} catch (err) {
console.log('> Sever initialization failed ', err.message);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment