[英]Access app.js variables in routes but without global 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文件的操作。 怎么解决???
我不确定我理解。 是不是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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.