Last active
September 20, 2017 12:24
-
-
Save milosjovac/cda180621e610ee0859ca31afaa5574b to your computer and use it in GitHub Desktop.
Permanent mongoose connection
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
var mongoose = require('mongoose') | |
let dbURI = 'localhost:27017/laimdb' | |
var timeToWaitOnConnection = 3000 // 3sec | |
var maxTimeToWaitOnConnection = 30000 // 30sec | |
mongoose.connection.on('error', function (error) { | |
console.error('Error in MongoDb connection: ' + error) | |
mongoose.disconnect() // force disconnect since connection.readyState is still 1 | |
}) | |
mongoose.connection.on('disconnected', function () { | |
console.log('MongoDB disconnected!') | |
setTimeout(connectWithRetry, timeToWaitOnConnection) | |
}) | |
let connectWithRetry = function () { | |
return mongoose.connect(dbURI, { server: { auto_reconnect: true } }, function (err) { | |
if (err) { | |
console.error('Failed to connect to MongoDb on startup - retrying in ' + (timeToWaitOnConnection / 1000) + ' sec') | |
if (timeToWaitOnConnection < maxTimeToWaitOnConnection) { | |
timeToWaitOnConnection += 1000 | |
} | |
} | |
}) | |
} | |
connectWithRetry() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment