Home > Software design >  How to fix MongoDB connection Error in AWS Lambda?
How to fix MongoDB connection Error in AWS Lambda?

Time:11-04

Hey, does Anyone face a MongoDB connection error/issue on AWS lambda? and if you know the solution, please help me, guys!

my code works perfectly in my local system!

But when I try to post, using the API gateway endpoint, MongoDB disconnect! ( session time-out error )

Image description

Image description

CodePudding user response:

This is because of your code that doesn't take care of lambda execution environment.

As mentioned in the comment above, between two lambda invocation, you are not releasing the connection to the DB. It is like doing two times in a row mongoose.connect()

I suggest to do something like this:

let cachedClient = null;

async function connectDB() {
  if (cachedClient) {
    return cachedClient;
  }

  // Connect to our MongoDB database hosted on MongoDB Atlas
  const client = await mongoose.connect(MONGO_DB_URL);

  cachedClient = client;
  return client;
}

This will reuse the same client across multiple lambda invocation (within the same execution environment). When a new lambda execution environment is created, cachedClient will be null and a new client will be created.

Hope it clarifies.

  • Related