什么是在快速中间件中使用monk / mongo的有效,正确的方法?

时间:2016-05-17 10:56:07

标签: node.js mongodb express monk

我正在开发一个网络应用程序。我发现CW Buechler's tutorial关于如何使一个简单的非常有用,但有一些令人烦恼的担忧,我想知道他们是真正的问题,还是我可以忽略的事情。

我将路由连接到数据库的方式直接来自教程。

在app.js中,此代码实例化数据库,并将对它的引用附加到通过中间件流动的每个req对象。

// wire up the database
var mongo = require('mongodb');
var db = require('monk')('localhost:27017/StarChamber');

----------8<-------

// Make our db accessible to our router
app.use(function(req,res,next){
    req.db = db;
    next();
});

在中间件中,它会像这样使用:

app.get('/', function (req, res) {
    var db = req.db;
    var collection = db.get('myCollection');
    // do stuff to produce results
    res.json (results);
});

所以,对我琐碎的担忧:

  1. 通过将数据库附加到req将数据库传递给路由非常方便,但它是否会影响性能?在我可以使用的路由器文件中引用它会更好吗?代码是做什么的?
  2. 在使用后放弃收藏是不错的做法?教程没有这样做,但是在退出路由处理程序之前进行collection.drop()调用看起来是有益的,否则我认为我只是与数据库建立了许多开放连接。
  3. 一如既往地感谢!

1 个答案:

答案 0 :(得分:4)

  1. No, it won't impact performance. It's a convenient method to pass a reference to db around, but with Monk it doesn't seem to be especially necessary. See below for an alternative setup.
  2. You are confusing collections with connections. The former are the MongoDB-equivalent of "tables" in SQL, so dropping them doesn't seem to make sense since that would basically throw away all the data in your database table. As for connections: through various layers of indirection, Monk seems to be using the official MongoDB Node driver, which handles connections itself (by means of a connection pool). So there's no need to handle it yourself.

For an alternative way of passing the Monk database handle around: you can place it in a separate module:

// database.js
module.exports = require('monk')('localhost:27017/StarChamber');

And in each module where you require the handle, you can import it:

var db = require('./database');