如何将变量传递给routes.index

时间:2012-01-05 19:22:19

标签: node.js mongodb express mongoose data-transfer

在文件app.js中我有:

  , mongoose = require('mongoose')
  , db = mongoose.connect('mongodb://localhost/expressdb');

  app.get('/', routes.index);

我有文件routes/index.js,如果我想将db变量转移到routes.index我该怎么办?

2 个答案:

答案 0 :(得分:3)

我已经通过将db作为参数传递给路由模块来设置一个如何实现这一点的示例,并且该模块返回一个函数(其中db是可见的):

<强> routes.index

module.exports = function (db) {
  return function(req, res, next) {
    // you can access db here
  }
}

<强> app.js

...
routes = {};
routes.index = require('./routes')(db);
...

答案 1 :(得分:1)

我认为,如果您尝试创建另一个连接(即:数据库接口是单例),那么连接到数据库以便共享连接的库中相当标准。您可以尝试简单地调用

db = mongoose.connect('mongodb://localeyes/expressdb');
在您的routes / index.js文件中

,它可能会使用相同的连接。我建议您阅读代码以查看它是否会使用现有连接,或者每次调用它时是否尝试重新连接。

编辑:第二个想法,你有另一种不那么美味的选择: 你可以把它变成全球性的

global.db = db;

然后在你的routes / index.js

var db = global.db;