我正在开发一个网络应用程序。我发现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);
});
所以,对我琐碎的担忧:
collection.drop()
调用看起来是有益的,否则我认为我只是与数据库建立了许多开放连接。一如既往地感谢!
答案 0 :(得分:4)
db
around, but with Monk it doesn't seem to be especially necessary. See below for an alternative setup.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');