在 koa2 中抽象一個 Mongodb 實例模塊。// mongoUtil.jsconst 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;在其他中間件中使用此模塊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;我知道在 require 返回一個的是 promise 對象,所以我使用時 const db = await mongo;。我現在想 mongoUtil.js 文件中直接返回 mongodb 實例對象,應該要怎么做???
- 1 回答
- 0 關注
- 1882 瀏覽
添加回答
舉報
0/150
提交
取消