javascript - koa2 通过MongoDB Driver链接 mongodb的疑惑?

查看:77
本文介绍了javascript - koa2 通过MongoDB Driver链接 mongodb的疑惑?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

//官方的文档如下:

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';
});

 ...

解决方案

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(),即可!

这篇关于javascript - koa2 通过MongoDB Driver链接 mongodb的疑惑?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆