Skip to content

Instantly share code, notes, and snippets.

@milosjovac
Last active September 20, 2017 12:24
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 milosjovac/cda180621e610ee0859ca31afaa5574b to your computer and use it in GitHub Desktop.
Save milosjovac/cda180621e610ee0859ca31afaa5574b to your computer and use it in GitHub Desktop.
Permanent mongoose connection
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