我一直在使用 MLab MongoDB 和 mongoose 库在无服务器 (Lambda) 处理程序中创建数据库连接。它在本地机器上运行顺利。但有时它在部署后不起作用。请求返回一个内部服务器错误
。奇怪的是有时它会起作用。但是如果我删除数据库连接代码,处理程序就会工作。无服务器日志只是说 Process exited before completing request
。没有真正的错误,所以不知道该怎么做。
数据库连接如下所示: 处理程序.js
// Connect to database
mongoose.connect(process.env.DATABASE_URL, {
useMongoClient: false
}).then((ee) => {
console.log('------------------------invoke db ', ee);
})
.catch(err => console.error('-----------error db ', err));
这里也没有错误。知道发生了什么吗?
最佳答案
当您看到 Process exited before completing request
时,这意味着 node
进程在 Lambda 能够调用 callback
之前已经崩溃。如果您转到 Cloudwatch 日志,将会有一个错误和所发生事件的堆栈跟踪。
您应该在您的处理程序中连接到 MongoDB 实例,并且在调用 callback()
之前,先断开连接。
应该是这样的……
exports.handler = (event, context, callback) => {
let response;
return mongoose.connect(process.env.DATABASE_URL, {
useMongoClient: false
}).then((ee) => {
// prepare your response
response = { hello: 'world' }
}).then(() => {
mongoose.disconnect()
}).then(() => {
// Success
callback(null, response)
}).catch((err) => {
console.error(err);
callback(err);
})
};
关于mongodb - Mongo 连接偶尔会使 lambda 函数超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46358050/