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

Menu