Connection to mongodb only fails inside an AWS Lambda

Hi guys!

I’m facing an error when trying to connect to a mongodb database that only happens inside an AWS Lambda. The same code being executed by a spike in my environment, using the same nodejs dependency versions, returns the expected result and creates a connection with mongodb without the slightest problem.

Another very similar connection code also works in Fargate containers on AWS ECS.

I’ve taken care of the network configuration, I’ve enabled public access. I no longer know what it could be.

Driver version: “mongodb”: “^6.3.0”
Connection string: “mongodb+srv://user:password@myapp-staging.ufqgvmg.mongodb.net/?retryWrites=true&w=majority” (I’ve changed some parameters, just to be on the safe side)

My code:

class MongoDbClientStore {
  constructor(args: IMongoDbClientStoreArgs) {
    this.driver = new MongoClient(args.connectionUri)

    this.database = args.database
    this.collection = args.collection
  }

  private readonly database: string
  private readonly collection: string
  private readonly driver: MongoClient

  async init() {
    try {
      await this.driver.connect() // fail here.
      await this.driver.db("admin").command({ ping: 1 });

      console.log('MongoDB connection successfully stabilized')

    } catch (err) {
      console.error('MongoDB connection failed: ', err)
    }
  }

Error returned:

ERROR   MongoDB connection failed:  MongoRuntimeError: Unable to parse ac-sgtcjuj-shard-00-00.ufqgvmg.mongodb.net:27017 with URL
    at new HostAddress (/var/task/index-2896b275.js:18304:34)
    at Function.fromString (/var/task/index-2896b275.js:18346:16)
    ... 4 lines matching cause stack trace ...
    at async MongoClient.connect (/var/task/index-2896b275.js:91527:13) {
  cause: TypeError: url_1.URL is not a constructor
      at new HostAddress (/var/task/index-2896b275.js:18301:19)
      at Function.fromString (/var/task/index-2896b275.js:18346:16)
      at /var/task/index-2896b275.js:89652:66
      at Array.map (<anonymous>)
      at resolveSRVRecord (/var/task/index-2896b275.js:89652:37)
      at async MongoClient._connect (/var/task/index-2896b275.js:91562:27)
      at async MongoClient.connect (/var/task/index-2896b275.js:91527:13),
  [Symbol(errorLabels)]: Set(0) {}

Thank you very much for all your help!

Hi @Luan_Melo,

Welcome to the MongoDB Community :sparkles:

Looking at the error message, it seems like the connection srv string is not getting parsed correctly. Could you make sure that you are passing the correct one and in a proper format in the code?

Can you directly hardcode it in your code and see if it resolves your issue or not? Alternatively, also check if the connection srv string works fine in your MongoDB shell and if it successfully connects you to your cluster or not.

Regards,
Kushagra