如何将 mongodb 数据库集合导出到另一个 js 文件?

How to export mongodb db collections to another js file?

我已经初始化了与我的 mongodb 的连接,现在将数据库导出到其他 nodejs 文件。我该怎么做?

我想到了类似的东西,但它给出了错误。

let database;
export const connectDB = async () => {
  const client = new MongoClient(config.dbUri, {
    useUnifiedTopology: true,
  });

  try {
    await client.connect();
    database = client.db('azkaben');
    logger.info('Connected to Database');
  } catch (e) {
    logger.error(e);
  } finally {
    await client.close();
  }
};

export default database

错误:数据库的未定义值

database 导入时将始终为 null。

connectDB 是 ync 调用,在它执行时您的数据库变量已经加载为 null。

connectDB 你可以从这里 return database

export const connectDB = async () => {
  const client = new MongoClient(config.dbUri, {
    useUnifiedTopology: true,
  });

  try {
    await client.connect();
    database = client.db('azkaben');
    return database; // you can get from here
    logger.info('Connected to Database');
  } catch (e) {
    logger.error(e);
  } finally {
    await client.close();
  }
};

更新代码
export const connectDB = async () => {
  if (database) return database; // return if database already connected. 
  const client = new MongoClient(config.dbUri, {
    useUnifiedTopology: true,
  });

  try {
    await client.connect();
    database = client.db('azkaben');
    return database; // you can get from here
    logger.info('Connected to Database');
  } catch (e) {
    logger.error(e);
  } finally {
    await client.close();
  }
};