javascript - koa2 通过MongoDB Driver链接 mongodb的疑惑?
高洛峰
高洛峰 2017-04-10 17:30:51
0
2
309
//官方的文档如下:

var MongoClient = require('mongodb').MongoClient
  , assert = require('assert');

// Connection URL
var url = 'mongodb://localhost:27017/myproject';

// Use connect method to connect to the server
MongoClient.connect(url, function(err, db) {
  assert.equal(null, err);
  console.log("Connected successfully to server");
  
  /* 连接后的各种操作,问题就在这里
  *  koa2中有很多条路由,难道每条路由中都要如此先连接mongodb,在回调中进行操作,最后关闭,这不科学吧!
  *  
  *  感觉应该是只建立一次连接,然后将连接成功后的 "db" 保存下来,在路由中随便使用,需要关闭的时候,直接调用 db.close(),断开连接;
  *  
  *  这个db在连接的回调函数中,怎么弄出去(像同步那样)?不知道弄了。。。
  *
  */ 

  db.close();
});


/* 找资料。。。自己瞎琢磨,得到如下方式,不知是否正确?
*
*  const MongoClient = require('mongodb').MongoClient;
*  export var db = (async function() {
*    try{
*      return await MongoClient.connect('mongodb://localhost:27017/myproject');
*    }catch(err){
*      console.log(err);
*    };
*  })();
*
* 用的时候在 Koa2的路由中,如下这样
* db.then((db)=>{
*    var collection = db.collection('documents');
*    collection.find({}).toArray(function(err, docs) {
*      console.log("Found the following records");
*      console.log(docs)
*    });
* });
*
*/


// koa2中的多条路由
router.get('/', (ctx, next) => {
  //这里需要查询数据库
  db.then((db)=>{
    ...

  });

  ctx.type = 'text/html; charset=utf-8';
  ctx.body = pug.renderFile('views/index.pug',{
    pageTitle:"Pug template engine",
    pretty:true
  });
});

router.get('/test', (ctx, next) => {
  //这里需要插入数据库
  db.then((db)=>{
    ...
    
  });
  ctx.body = 'Hello Koa2';
});

 ...

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

répondre à tous(2)
阿神

GitHub上找到了项目monk,可以满足需求!

const db = require('monk')('localhost/mydb') //连接mongdb
const users = db.get('users')                //选择集合


router.get('/', async(ctx, next) => {
  //这里增删改查操作,注意 users.find({}, {sort: {name: 1}}),返回promise对象
  let data = await users.find({}, {sort: {name: 1}});
  ctx.body = data;
});

需要断开链接是 db.close(),即可!
巴扎黑

建议你用sequelizejs比较热门的orm框架

Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!