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?