closuresmongoose连接Lambda

我在Amazon Web Services中使用Lambda函数发现了一个奇怪的行为。

我使用的是Node 4.3和Mongoose 4.4.17

这个想法是testing和玩Lambda的function。

我做一个简单的模型,我把它存储在一个Ec2实例。 代码工作正常,直到我尝试closures连接。 我知道,更好的做法是“不要把你连接起来,让游泳池处理”。 那么,这适用于一个正常的应用程序,但Lambda是一个无状态函数,所以如果我不closures连接,这保持开放,消耗资源。 如果每秒有数千个请求,这可能会非常糟糕。

所以,这是我的代码。

'use strict'; let mongoose = require('mongoose'); //I add this options, because this close my connections //faster than the 30 min by default let options = { server: { socketOptions: { keepAlive: 30000, connectTimeoutMS: 30000 } }}; let db = mongoose.createConnection('mongodb://myInternalServerEC2:27017/myDB', options); let Schema = require('mongoose').Schema; let TempSchema =new Schema({name:{type:String,required:true}}); //This is a copy paste from an another project, //but i can remove, but i don't think this has nothing //with my problem. personSchema.set('autoIndex', false); personSchema.index({name:1}); let tempDB = db.model('tempcol', TempSchema); exports.handler = (event, context, callback) => { tempDB.find(function (err, data) { if (typeof(data) === 'object' && data.length === 0) { data = null; } if (!err && data !== null) { callback(null, data); } else if (!err) { error = new Error("No data found"); callback(error); } else { callback(err); } }).populate('_typeId'); }; 

此代码工作没有问题。

现在…让我们尝试closures连接。 (哈哈)

我使用if在任何情况下,在if的结尾,if在find函数之后,等等。

 db.close(); callback(null, data); mongoose.disconnect(); callback('Some error'); //This finish inside the find function finish(db, function(){ callback(error, data); }); // A finish function with a callback, // so i can call the parent callback function finish(db, cb){ db.close(function(){ cb(); }); } 

在每一个案件。 Lambda函数永远不会返回错误,只返回NULL。

任何人都有一些线索为什么这种行为在Lambda? 在本地模式下,这种行为从来没有发生过我。

如果我删除closures指令,lambda函数返回从我的Mongo服务器的数据

提前

我发现了这个问题。

问题是上下文。 和callback。 我更改代码以在处理程序中包含createConnection事件。

https://aws.amazon.com/es/blogs/compute/getting-nodejs-and-lambda-to-play-nicely/

此代码工作。

 'use strict'; let mongoose = require('mongoose'); let options = { server: { socketOptions: { keepAlive: 30000, connectTimeoutMS: 30000 } }}; let Schema = require('mongoose').Schema; let TempSchema =new Schema({name:{type:String,required:true}}); TempSchema.set('autoIndex', false); TempSchema.index({name:1}); exports.handler = (event, context) => { let db = mongoose.createConnection('mongodb://myInternalServerEC2:27017/myDB', options); let tempDB = db.model('tempcol', TempSchema); function closeBD(cbk){ console.log("Close BD"); db.close(function(){ cbk(); }); } tempDB.find(function (err, data) { if (typeof(data) === 'object' && data.length === 0) { data = null; } if (!err && data !== null) { context.succeed(data); } else if (!err) { let error = new Error("No data found"); context.fail(error); } else { context.fail(err); } closeBD(function(){ context.done(); }); }); }; 

希望有人find这个有用的。