简体   繁体   English

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

[英]Access app.js variables in routes but without global express

This is my config in 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);

In routes/index.js i have: 在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);

    })

})
};

it is of course not working unless i remove "var" from "db" in app.js, then it became global and i can access it in routes, but i don't want globals in my code and don't want to move controllers actions to app.js file. 它当然不起作用,除非我从app.js中的“db”中删除“var”,然后它变成了全局,我可以在路由中访问它,但我不想在我的代码中使用全局变量并且不想移动控制器对app.js文件的操作。 How to fix it ??? 怎么解决???

I'm not sure I understand. 我不确定我理解。 Isn't db global with or without var ( it looks like a global scope for me )? 是不是db全球有或无var (它看起来像我的一个全局范围)? Besides, why don't you want it to be global? 此外,你为什么不想让它成为全球性的呢? That's a good example of using globals. 这是使用全局变量的一个很好的例子。

But it won't get shared between files. 但它不会在文件之间共享。 You have to add it to exports. 您必须将其添加到导出。 Try this: 尝试这个:

app.js app.js

exports.db = db;

routes/index.js 路线/ index.js

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

The other way is to add db to every handler like this: 另一种方法是将db添加到每个处理程序,如下所示:

app.js app.js

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

Then it should be available in any route as req.db . 然后它应该在任何路由中可用作req.db

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM