MongoDB闲置问题给我带来了噩梦。它会无故失败,不会触发断开事件或错误。它只是在API调用过程中断开连接。
我也尝试阅读博客和旧问题,并尝试了所有方法,但这种情况根本没有帮助。
这是我的数据库连接代码:
function connect () {
return mongoose.connect(process.env.MONGO_DB_URI, {
useNewUrlParser: true,
reconnectTries: Number.MAX_VALUE,
reconnectInterval: 1000,
bufferMaxEntries: 0, // and MongoDB driver buffering
bufferCommands: false, // Disable mongoose buffering
ha: true, // Make sure the high availability checks are on
haInterval: 10000 // Run every 10 seconds
})
}
if (process.env.MONGO_DB_URI) {
connect()
}
与此同时,我也正在为数据库记录多个事件。
db.on('connecting', () => {
debug(`mongoose : connecting `)
})
db.on('connected', () => {
debug(`mongoose : connected`)
})
db.on('open', () => {
debug(`mongoose : open`)
})
db.on('disconnecting', () => {
debug(`mongoose : disconnecting`)
})
db.on('disconnected', () => {
debug(`mongoose : disconnected`)
})
db.on('close', () => {
debug(`mongoose : close`)
})
db.on('reconnected', () => {
debug(`mongoose : reconnected`)
})
db.on('error', (err) => {
debug(`mongoose : error`, err)
})
db.on('all', () => {
debug('mongoose: all')
})
db.on('fullsetup', () => {
debug(`mongoose : fullsetup`)
})
在调用API之前,我还要从中间件检查数据库连接。
app.use(async (req, res, next) => {
log.info('Ready State: ' + mongoose.connection.readyState, {
action: 'App.ConnectionCheck'
})
if (mongoose.connection.readyState !== 1) {
log.info('try to reconnect', {
action: 'App.ConnectionCheck'
})
await connect()
next()
} else if (mongoose.connection && mongoose.connection.db) {
await Promise.race([
mongoose.connection.db.admin().ping(),
new Promise((resolve, reject) => {
setTimeout(() => {
reject(new Error('Race condition failed'))
}, 1000)
})
])
.then(async d => {
log.info('ping successful: ', d)
if (d.ok !== 1) {
await connect()
}
})
.catch(async e => {
log.error('Ping Failed ', {
error: e
})
await connect()
})
next()
} else {
next()
}
})
但是仍然有时会打来电话,并进行第一个查询,但是我没有得到响应,我的API超时。
这是我的日志的样子,请注意重新连接所需的时间。
2020-08-10 16:30:55.465 (+05:00) 34c5812c-5446-4c0f-bddf-c4ca8a0117cb INFO ----------------- BODY END ------------
2020-08-10 16:30:55.466 (+05:00) 34c5812c-5446-4c0f-bddf-c4ca8a0117cb INFO Mongoose: meetings.countDocuments({ appntId: '<APP_ID_HERE>', '$or': [ { deleted: true }, { createdAt: { '$gt': new Date("Mon, 10 Aug 2020 11:30:45 GMT") } {})
Mon, 10 Aug 2020 11:30:55 GMT timify:db-handle:index mongoose : disconnected
Mon, 10 Aug 2020 11:31:15 GMT timify:db-handle:index mongoose : connected
Mon, 10 Aug 2020 11:31:15 GMT timify:db-handle:index mongoose : reconnected
END RequestId: 34c5812c-5446-4c0f-bddf-c4ca8a0117cb
END RequestId: 34c5812c-5446-4c0f-bddf-c4ca8a0117cb
REPORT RequestId: 34c5812c-5446-4c0f-bddf-c4ca8a0117cb Duration: 30030.13 ms Billed Duration: 30000 ms Memory Size: 10
Max Memory Used: 172 MB
版本:
我看到了有关此问题的另一篇文章,但是我的环境有所不同,该问题可以追溯到2016年。
答案 0 :(得分:0)
在AWS Lambda上运行Express应用程序时遇到了类似的问题。
我得到的错误消息是:
MongooseError: Cannot call `users.find()` before initial connection is complete if `bufferCommands = false`. Make sure you `await mongoose.connect()` if you have `bufferCommands = false`.
我当前有效的连接设置为
mongoose
.connect(mongoConnectionString, {
useNewUrlParser: true ,
useCreateIndex: true,
useUnifiedTopology: true,
keepAlive : true,
bufferMaxEntries: 0 // and MongoDB driver buffering
}
);
通过反复试验,我设法找到了连接错误
bufferCommands:错误
命令并对其进行注释使它对我有用。
我无法通过mongoose documentation找到有关缓冲选项的任何原因,但是您可以尝试通过以下方式全局关闭缓冲,
mongoose.set('bufferCommands', false);
希望此解决方案有帮助。
EDIT:将bufferCommands全局设置为false会导致相同的错误。