title: Close Mongoose connection Lambda
body: <p>I found a weird behavior using a Lambda function in Amazon Web Services.</p>
  
  <p><em>I'm using Node 4.3 and Mongoose 4.4.17</em></p>
  
  <p>The idea is to test and play with the capabilities of Lambda. </p>
  
  <p>I make a simple model and i store it in a Ec2 instance. The code works fine until i try to close the connection. I know, better practices say "Don't close you connection, let the pool handle." Well, this apply in a normal Application, but Lambda is a stateless function, so if i don't close the connection this keeps open, consuming resources. And this could be really bad when you have thousands of requests per second.</p>
  
  <p>So, this is my code.</p>
  
  <pre><code>'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) =&gt; {
      tempDB.find(function (err, data) {
          if (typeof(data) === 'object' &amp;&amp; data.length === 0) {
              data = null;
          }
          if (!err &amp;&amp; data !== null) {
              callback(null, data);
          } else if (!err) {
              error = new Error("No data found");
              callback(error);
          } else {
              callback(err);
          }
      }).populate('_typeId');
  };
  </code></pre>
  
  <p>This code Works without problems.</p>
  
  <p>Now... lets try to close the connection. (Ha ha) </p>
  
  <p>I use this in any case of the ifs, at the end of the if, after the if inside the find function, etc.</p>
  
  <pre><code>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();
      });
  }
  </code></pre>
  
  <p>In every single case. The Lambda function never returns an error, only returns NULL.</p>
  
  <p>Anyone has some clue why this behavior in Lambda? In local mode, this behavior never happens to me before.</p>
  
  <p>If i remove the close instruction, the lambda function returns data from my Mongo server</p>
  
  <p>Thks in advance</p>