这是我在 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 文件的操作。怎么解决???