'How do you store a MongoClient connection in a variable for later use?

This is probably a very simple question. I am running into an issue when storing a MongoClient connection in a variable for later use. Using import { MongoClient } from 'mongodb'

  static async connectDB(connectionConfig, additionalConfig) {
// destructure this
try {
  let mongoURI = ''

  const dbPass =
    connectionConfig.user && connectionConfig.password
      ? `${connectionConfig.user}:${connectionConfig.password}@`
      : null

  if (dbPass === null)
    mongoURI = `mongodb://${connectionConfig.host}:${connectionConfig.port}/${connectionConfig.database}`
  else
    mongoURI = `mongodb+srv://${userPass}${connectionConfig.host}/${connectionConfig.database}?retryWrites=true&w=majority`

  const client = new MongoClient(mongoURI)
  await client.connect()

  return client
} catch (err) {
  return { err }
}}

As you can see in the above function, I connect and return the client, but when I attempt to use the client in the below function, I get the error

MongoRuntimeError: Connection pool closed

  static async collectionExists(dbConn, modelName) {
try {
  console.log(dbConn.connection.db()) // this returns what you'd expect it to
  const collections = await dbConn.connection // this is where it fails
    .db()
    .listCollections()
    .toArray()
  console.log(collections)

  return true
} catch (err) {
  return { err }
}}

Thank you for your help!



Solution 1:[1]

My issue was I was closing the connection before accessing Mongo. I made the rookie mistake of misusing the "await" keyword outside an async function. Just remember, all code, whether it's right or wrong, will do exactly what you tell it to. Thank you!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Joel Mason