基于@zangw 的回答,我已经为我的应用程序完成了这个数据库初始化函数
const mongoose = require('mongoose')
const RETRY_TIMEOUT = 3000
module.exports = function initDB () {
mongoose.Promise = global.Promise
const options = {
autoReconnect: true,
useMongoClient: true,
keepAlive: 30000,
reconnectInterval: RETRY_TIMEOUT,
reconnectTries: 10000
}
let isConnectedBefore = false
const connect = function () {
return mongoose.connect(process.env.MONGODB_URL, options)
.catch(err => console.error('Mongoose connect(...) failed with err: ', err))
}
connect()
mongoose.connection.on('error', function () {
console.error('Could not connect to MongoDB')
})
mongoose.connection.on('disconnected', function () {
console.error('Lost MongoDB connection...')
if (!isConnectedBefore) {
setTimeout(() => connect(), RETRY_TIMEOUT)
}
})
mongoose.connection.on('connected', function () {
isConnectedBefore = true
console.info('Connection established to MongoDB')
})
mongoose.connection.on('reconnected', function () {
console.info('Reconnected to MongoDB')
})
// Close the Mongoose connection, when receiving SIGINT
process.on('SIGINT', function () {
mongoose.connection.close(function () {
console.warn('Force to close the MongoDB connection after SIGINT')
process.exit(0)
})
})
}
有一些区别:我添加了一些选项来防止连接关闭问题 - 自动重试 30 次后没有重新连接,只是 MongoError: Topology was destroy for any operation and no reconnect; 我还在连接后添加了 .catch 以防止未处理的承诺拒绝):