Created
October 20, 2015 16:18
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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