2013-02-23 28 views
2

這是我在app.js配置:訪問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); 

在路由/ 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」,然後它變成全局的,我可以在路由中訪問它,但我不想在我的代碼中使用全局變量,也不想將控制器操作移動到應用程序.js文件。如何解決它?

回答

9

我不確定我是否理解。是不是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

+0

它實際上只是它的全局文件,當它與var - 當我刪除它 - 成爲全球和所有文件的可用性。感謝您的幫助 - 它運作良好:) – Kriss 2013-02-23 09:59:54

+0

如何從routes/index.js獲取anyObj? //app.js const的應用程式=快遞() const的路由=要求( './路由 ') app.use('/',路由) app.set( 'anyObj',{} ) //路由/ index.js 常量表達=要求( '表示') const的路由器= express.Router() const的用戶需要=(」 ./用戶 ') router.use('/ api/users',用戶) – aung 2017-07-19 00:55:21