Skip to content

Instantly share code, notes, and snippets.

@callingmedic911
Last active November 29, 2018 08:07
Show Gist options
  • Save callingmedic911/f58c0336d5285d805881b2566d6c6f8e to your computer and use it in GitHub Desktop.
Save callingmedic911/f58c0336d5285d805881b2566d6c6f8e to your computer and use it in GitHub Desktop.
var mongoose = require('mongoose');
var dbURL = 'mongodb://localhost:27017/testtest';
var retryMaxAttempt = 60;
var retryInterval = 1000;
var retryCountFirstConnect = 0;
mongoose.connect(dbURL, {
reconnectTries: retryMaxAttempt,
reconnectInterval: retryInterval
});
mongoose.connection.on('open', function(){
console.log("Opened connection ", dbURL);
});
mongoose.connection.on('connected', function(){
console.log("Connected connection ", dbURL);
});
mongoose.connection.on('error', function(err){
if (err.message
&& err.message.match(/failed to connect to server .* on first connect/)
&& retryCountFirstConnect < retryMaxAttempt) {
console.log(new Date(), String(err));
setTimeout(function () {
console.log("Retrying first connect...");
mongoose.connection.openUri(dbURL).catch(() => {});
}, retryInterval);
retryCountFirstConnect++;
} else {
console.error(new Date(), String(err));
}
});
mongoose.connection.on('close', function() {
console.log("Closed connection");
});
mongoose.connection.on('disconnected', function(){
console.log("Disconnected");
});
mongoose.connection.on('reconnected', function(){
console.log("Reconnected ", dbURL);
});
@callingmedic911
Copy link
Author

Taken from: Automattic/mongoose#5169 (comment)

Empty catch is required.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment