1.根目錄/module/config.jsjavascript
/** * 配置文件 */ var app = { dbUrl: 'mongodb://127.0.0.1:27017/?gssapiServiceName=mongodb', dbName: 'koa' } module.exports = app;
2.根目錄/module/db.jshtml
/** * DB庫 */ var MongoClient = require('mongodb').MongoClient; var Config = require('./config.js'); class Db { /** * 單例 * 解決屢次實例化,實例不共享的問題 */ static getInstance() { if (!Db.instance) { Db.instance = new Db(); } return Db.instance; } constructor() { this.dbClient = ''; /*屬性 存放db對象*/ this.connect(); /*實例化的時候就鏈接數據庫*/ } connect() { /*鏈接數據庫*/ let _that = this; return new Promise((resolve, reject) => { if (!_that.dbClient) { /*解決數據庫屢次鏈接的問題*/ MongoClient.connect(Config.dbUrl, (err, client) => { if (err) { reject(err); } else { _that.dbClient = client.db(Config.dbName); resolve(_that.dbClient); } }) } else { resolve(_that.dbClient); } }) } find(collectionName, json) { return new Promise((resolve, reject) => { this.connect().then((db) => { var result = db.collection(collectionName).find(json); result.toArray((err, docs) => { if (err) { reject(err); return; } resolve(docs); }) }) }) } insert() { // } } module.exports = Db.getInstance();
3.根目錄/app.jsjava
// 引入模塊 const Koa = require('koa'); const router = require('koa-router')(); /*引入是實例化路由 推薦*/ const render = require('koa-art-template'); const path = require('path'); const DB = require('./module/db.js'); // 實例化 let app = new Koa(); // 配置 koa-art-template 模板引擎 render(app, { root: path.join(__dirname, 'views'), // 視圖的位置 extname: '.html', // 後綴名 debug: process.env.NODE_ENV !== 'production' // 是否開啓調試模式 }) router.get('/', async (ctx) => { console.time('start1'); let result = await DB.find('user', {}); console.log(result); console.timeEnd('start1'); await ctx.render('index', { list: { name: '張三' } }); }) router.get('/news', async (ctx) => { console.time('start2'); let result = await DB.find('user', {}); console.log(result); console.timeEnd('start2'); ctx.body = '新聞頁面'; }) app.use(router.routes()); app.use(router.allowedMethods()); app.listen(3000);
.mongodb