Close Mongoose connection Lambda Close Mongoose connection Lambda mongoose mongoose

Close Mongoose connection Lambda


I found the problem.

The problem is the context. And the callbacks. I change the code to include the createConnection event inside the handler.

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

This code works.

'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();        });    });};

Hope someone find this usefull.