如何将 MongoClient 连接存储在变量中供以后使用?

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

这可能是一个非常简单的问题。在变量中存储 MongoClient 连接供以后使用时,我 运行 遇到了问题。从 'mongodb'

使用 import { MongoClient }
  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 }
}}

正如您在上面的函数中看到的,我连接并 return 客户端,但是当我尝试在下面的函数中使用客户端时,出现错误

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 }
}}

感谢您的帮助!

我的问题是我在访问 Mongo 之前关闭了连接。我犯了一个新手错误,即在异步函数之外滥用“await”关键字。请记住,所有代码,无论是对还是错,都会完全按照您的指示执行。谢谢!