Silent fail connecting to Atlas from AWS Lambda

I’m honestly not sure if this is a Mongo question or an AWS question, but I’m having difficulty connecting to an Atlas instance from a Lambda function. The code posted below works exactly as expected when I run it from a local instance, but when I try to run it from the Lambda the “start” log fires but it never reaches the “connected” line after await client.connect();. There is no error - it just silently fails and thinks it succeeded. I’m almost completely new to Mongo so I’m not sure where I should start trying to investigate this. Any help is greatly appreciate.

const { MongoClient, ServerApiVersion } = require("mongodb");

const url =
  "mongodb+srv://mrcool:password@a.real.uri.goes.here/?retryWrites=true&w=majority";

const client = new MongoClient(url, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
  serverApi: ServerApiVersion.v1,
});

const doStuff = async () => {
  console.log("start");
  await client.connect();
  console.log('connected');
  const db = client.db("test");
  const collection = db.collection("cats");
  const cats = await collection.find({}).toArray();
  console.log(cats);
  return cats;
};

const handler = async () => {
  doStuff()
    .catch((err) => {
      console.error(err);
    })
    .finally(() => client.close());
};

exports.handler = handler;

Hi @Kellen_Barber ,

Welcome to The MongoDB Community Forums! :wave:

I think there could be some issue with your setup or code but as you are not catching the error in logs hence you are not able to see it. Please consider using a try catch block with await client.connect(); as below

try {
      await client.connect();
   
        } 
catch (e) {
            console.error(e);
           }

Additionally, I would recommend you to go through this doc on Manage Connections with AWS Lambda.

Regards,
Tarun

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.