简体   繁体   中英

Access app.js variables in routes but without global express

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

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. 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 )? 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

exports.db = db;

routes/index.js

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

The other way is to add db to every handler like this:

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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