在路由中访问app.js变量但没有全局表达

时间:2013-02-23 09:29:55

标签: node.js express

这是我在app.js中的配置:

var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, http = require('http')
, path = require('path')
, Server = mongo.Server
, Db = mongo.Db;
, mongo = require('mongodb');
, BSON = mongo.BSONPure;


var app = express();
var server = new Server('localhost', 27017, {auto_reconnect: true, });
var db = new Db('tasksdb', server); //i need to remove this "var" to access db in routes


db.open(function(err, db) {
if(!err) {
 console.log("Connected to 'tasksdb' database");
 db.collection('tasks', {safe:true}, function(err, collection) {
   if (err) {
     console.log("The 'tasks' collection doesn't exist. Creating it with sample data...");
     populateDB();
   }
 });
}
});

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

在routes / index.js中我有:

exports.index = function(req, res){
  res.render('index', { title: 'Express' });
};

exports.getAllTasks = function (req, res) {

db.collection( 'tasks', function ( err, collection ){ //this "db" is not accessible unless i remove "var" from db in app.js

    collection.find().toArray( function ( err, items ) {

        res.send(items);

    })

})
};

它当然不起作用,除非我从app.js中的“db”中删除“var”,然后它变成了全局,我可以在路由中访问它,但我不想在我的代码中使用全局变量而不是想要将控制器操作移动到app.js文件。怎么解决???

1 个答案:

答案 0 :(得分:10)

我不确定我理解。是db全局是否有var(它看起来像是我的全球范围)?此外,你为什么不想让它成为全球性的呢?这是使用全局变量的一个很好的例子。

但它不会在文件之间共享。您必须将其添加到导出。试试这个:

<强> app.js

exports.db = db;

<强>路由/ index.js

var db = require("app").db;

另一种方法是将db添加到每个处理程序中:

<强> app.js

app.use(function(req,res,next){
    req.db = db;
    next();
});
app.get('/', routes.index);
app.get('/tasks', routes.getAllTasks);

然后它应该在req.db的任何路线中可用。