title: AWS lambda with mongoose to Atlas - MongoNetworkError
body: <p>I am trying to connect MongoDB Atlas with mongoose and aws lambda but i get error MongoNetworkError</p>
  
  <ul>
  <li>AWS Lambda</li>
  <li>Mongoose</li>
  <li>MongoDB Atlas</li>
  </ul>
  
  <p>The same code was tested with <code>serverless-offline</code> and works perfect, the problem is when i deploy it to AWS Lambda.</p>
  
  <p>This is the code snipet</p>
  
  <pre><code>'use strict';
  const mongoose = require('mongoose');
  const MongoClient = require('mongodb').MongoClient;
  let dbuser  = process.env.DB_USER;
  let dbpass = process.env.DB_PASSWORD;
  let opts = { 
      bufferCommands: false, 
      bufferMaxEntries: 0, 
      socketTimeoutMS: 2000000, 
      keepAlive: true, 
      reconnectTries: 30, 
      reconnectInterval: 500,
      poolSize: 10,
      ssl: true,
   };
  const uri = `mongodb+srv://${dbuser}:${dbpass}@carpoolingcluster0-bw91o.mongodb.net/awsmongotest?retryWrites=true&amp;w=majority`;
  // simple hello test
  module.exports.hello = async (event, context, callback) =&gt; {
      const response = {
          body: JSON.stringify({message:'AWS Testing :: '+ `${dbuser} and ${dbpass}`}),
      };
      return response;
  };
  // connect using mongoose
  module.exports.cn1 = async (event, context, callback)  =&gt; {
      context.callbackWaitsForEmptyEventLoop = false;
      let conn = await mongoose.createConnection(uri, opts);
      const M = conn.models.Test || conn.model('Test', new mongoose.Schema({ name: String }));
      const doc = await M.find();
      const response = {
          body: JSON.stringify({data:doc}),
      };
      return response;
  };
  // connect using mongodb
  module.exports.cn2 = (event, context, callback) =&gt; {
      context.callbackWaitsForEmptyEventLoop = false;
      console.log("Connec to mongo using connectmongo ");
      MongoClient.connect(uri).then(client =&gt; {
          console.log("Success connect to mongo DB::::");
          client.db('awsmongotest').collection('tests').find({}).toArray()
              .then((result)=&gt;{
                  let response = {
                      body: JSON.stringify({data:result}),
                  }
                  callback(null, response)
              })
      }).catch(err =&gt; {
          console.log('=&gt; an error occurred: ', err);
          callback(err);
      });
  };
  </code></pre>
  
  <p>In the CloudWatch logs i see this error</p>
  
  <pre><code>{
      "errorType": "MongoNetworkError",
      "errorMessage": "failed to connect to server [carpoolingcluster0-shard-00-02-bw91o.mongodb.net:27017] on first connect [MongoNetworkError: connection 5 to carpoolingcluster0-shard-00-02-bw91o.mongodb.net:27017 closed]",
      "stack": [
          "MongoNetworkError: failed to connect to server [carpoolingcluster0-shard-00-02-bw91o.mongodb.net:27017] on first connect [MongoNetworkError: connection 5 to carpoolingcluster0-shard-00-02-bw91o.mongodb.net:27017 closed]",
          "    at Pool.&lt;anonymous&gt; (/var/task/node_modules/mongodb-core/lib/topologies/server.js:431:11)",
          "    at Pool.emit (events.js:189:13)",
          "    at connect (/var/task/node_modules/mongodb-core/lib/connection/pool.js:557:14)",
          "    at callback (/var/task/node_modules/mongodb-core/lib/connection/connect.js:109:5)",
          "    at runCommand (/var/task/node_modules/mongodb-core/lib/connection/connect.js:129:7)",
          "    at Connection.errorHandler (/var/task/node_modules/mongodb-core/lib/connection/connect.js:321:5)",
          "    at Object.onceWrapper (events.js:277:13)",
          "    at Connection.emit (events.js:189:13)",
          "    at TLSSocket.&lt;anonymous&gt; (/var/task/node_modules/mongodb-core/lib/connection/connection.js:350:12)",
          "    at Object.onceWrapper (events.js:277:13)",
          "    at TLSSocket.emit (events.js:189:13)",
          "    at _handle.close (net.js:597:12)",
          "    at TCP.done (_tls_wrap.js:388:7)"
      ],
      "name": "MongoNetworkError",
      "errorLabels": [
          "TransientTransactionError"
      ]
  }
  </code></pre>
  
  <p>Here is example on github to reproduce the error.</p>
  
  <p><a href="https://github.com/rollrodrig/error-aws-mongo-atlas" rel="nofollow noreferrer">https://github.com/rollrodrig/error-aws-mongo-atlas</a></p>
  
  <p>Just clone it, npm install, add your mongo atlas user, password and push to AWS.</p>
  
  <p>Thanks.</p>