Export Asynchronous return value in Koa2

Abstract a Mongodb instance module in koa2.

// mongoUtil.js
const MongoClient = require("mongodb").MongoClient;

async function getMongoDB() {
  try {
    const client = await new MongoClient("mongodb://localhost:27017/test").connect();
    db = client.db();

    return db;
  } catch (err) {
    client.close();
  }
}

module.exports = getMongoDB;

use this module in other middleware

const router = require("koa-router")();
let mongo = require("../db/mongoUtil")();

router.get("/test", async (ctx, next) => {
  ctx.body = {"Koa": "Hello World"};

  const db = await mongo;
  const col = db.collection("log");

  const cursor = col.find({});

  while(await cursor.hasNext()) {
    const doc = await cursor.next();
    console.dir(doc);
  }
});

module.exports = router;

I know that a promise object is returned in require, so I use const db = await mongo; .

now I want to return the mongodb instance object directly in the mongoUtil.js file. What should I do?

Aug.17,2021

http://mongodb.github.io/node.

take a look at this official example
just module.exports = client
without await it connect
just connect it once in your mongoUtil
require code will only execute once
when your connect is not ready
mongo will automatically put all your operations on the database into a queue and wait for connect to be ready. No reason

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b326cd-4039e.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b326cd-4039e.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?