[英]Lambda NodeJS not inserting into MongoDB
我正在尝试编译一个使用 Mongoose 的 Lambda 函数,但数据库似乎没有发生任何事情? 没有控制台日志等。这是我当前的代码:
索引.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);
});
});
});
数据库.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);
});
};
模型/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 测试,似乎都没有添加到日志中,我在日志中获得的信息非常少。
请注意context.callbackWaitsForEmptyEventLoop = false;
. 这个错误标志意味着:每当 lambda 完成您的处理程序函数的执行时,它会立即终止进程,即使事件循环中还有一些东西需要处理。 在您的情况下,您的处理程序函数向 mongodb 发出一个承诺请求,但您不会await
该承诺。 您只需启动它并让它在后台工作,但由于我之前提到的那个错误标志,即使 lambda 看到在事件循环中存在要处理的网络 I/O,它也会立即终止进程。 这就是为什么您甚至看不到任何日志的原因-甚至不执行承诺的 then 或 catch 语句。
因此,如果您出于目的在后台查询 mongodb,我建议您删除该错误标志。 如果您不需要在后台执行此操作,请将await
添加到您的 mongodb 查询中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.