Skip to content

Instantly share code, notes, and snippets.

@richzw
Created January 7, 2016 14:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save richzw/3fe799f384a2037e963f to your computer and use it in GitHub Desktop.
Save richzw/3fe799f384a2037e963f to your computer and use it in GitHub Desktop.
var mongoose = require('mongoose');
var isSeenConnected = false;
var connect = function() {
var opt = { server: { auto_reconnect: true } };
mongoose.connect('mongodb://localhost/' + 'test', opt);
};
connect();
mongoose.connection.on('error', function() {
console.log('Could not connect to mongoDB');
});
mongoose.connection.on('open', function() {
console.log('Open connection to mongoDB');
});
mongoose.connection.on('disconnected', function() {
console.log('Lost mongoDB connection...');
if (!isSeenConnected)
connect();
});
mongoose.connection.on('connected', function() {
isSeenConnected = true;
console.log('Establish connection to mongoDB');
});
mongoose.connection.on('reconnected', function() {
console.log('Reconnected to mongoDB');
});
process.on('SIGINT', function() {
mongoose.connection.close(function() {
console.log('Force to close the connection with mongoDB');
process.exit(0);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment