我正在尝试编译使用Mongoose的Lambda函数,但数据库似乎没有任何反应?没有控制台日志等。这是我当前的代码:
index.js
const connectToDatabase = require('./db');
const Match = require('./models/Match');
exports.handler = async (event, context, callback) => {
context.callbackWaitsForEmptyEventLoop = false;
let player_1_name = 'test name';
let player_1_network = 'test network';
let match_id = 1;
connectToDatabase().then(() => {
var MyModel = new Match({
player_1_name: player_1_name,
player_1_network: player_1_network,
match_id: match_id
});
MyModel.save().then(() => {
console.log('Data saved');
}).catch(e => {
console.log(e);
});
});
});
db.js
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
let isConnected;
module.exports = connectToDatabase = () => {
if (isConnected) {
console.log('=> using existing database connection');
return Promise.resolve();
}
console.log('=> using new database connection');
return mongoose.connect(process.env.DB, {useMongoClient: true}).then(db => {
isConnected = db.connections[0].readyState;
}).catch(e => {
console.log('Error while DB connecting');
console.log(e);
});
};
models / Match.js
const mongoose = require('mongoose');
const MatchSchema = new mongoose.Schema({
player_1_name: {
type: String,
required: true
},
player_1_network: {
type: String,
required: true
},
player_1_matches: {
type: Number,
default: 0
},
player_1_kills: {
type: Number,
default: 0
},
player_1_last_updated: {
type: Date,
default: null
},
player_2_name: {
type: String,
default: null
},
player_2_network: {
type: String,
default: null
},
player_2_matches: {
type: Number,
default: 0
},
player_2_kills: {
type: Number,
default: 0
},
player_2_last_updated: {
type: Date,
default: null
},
match_id: {
type: Number,
required: true
},
status: {
type: Boolean
},
});
module.exports = mongoose.model('Match', MatchSchema);
运行任何测试(无论是通过API网关还是直接进行Lambda测试)时,似乎都没有添加任何日志,我在日志中所获得的只是很少的信息。
答案 0 :(得分:1)
请注意显示context.callbackWaitsForEmptyEventLoop = false;
的行。此false标志表示以下含义:每当lambda完成处理程序函数的执行时,即使事件循环中有待处理的内容,它也会立即终止进程。在您的情况下,您的处理函数会向带有承诺的mongodb发送请求,但您不会await
对该承诺进行请求。您只需旋转它并使其在后台运行,但是由于我前面提到的那个错误标志,lambda会立即终止该过程,即使它看到事件循环中有要处理的网络I / O。这就是为什么您甚至看不到任何日志的原因-然后甚至没有执行promise的catch语句。
因此,如果您出于特定目的在后台查询mongodb,建议您删除该错误标志。如果您不需要在后台执行此操作,请在您的mongodb查询中添加await
。