@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 destroyed for any operation and no reconnect; また、未処理の約束の拒否を防ぐために、接続後に .catch を追加しました):