这是我在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);
Run Code Online (Sandbox Code Playgroud)
在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);
})
})
};
Run Code Online (Sandbox Code Playgroud)
它当然不起作用,除非我从app.js中的"db"中删除"var",然后它变成了全局,我可以在路由中访问它,但我不想在我的代码中使用全局变量并且不想移动控制器对app.js文件的操作.怎么解决???
fre*_*ish 10
我不确定我理解.是不是db全球有或没有var(它看起来像我的全球范围)?此外,你为什么不想让它成为全球性的呢?这是使用全局变量的一个很好的例子.
但它不会在文件之间共享.您必须将其添加到导出.试试这个:
app.js
exports.db = db;
Run Code Online (Sandbox Code Playgroud)
路线/ index.js
var db = require("app").db;
Run Code Online (Sandbox Code Playgroud)
另一种方法是添加db到每个处理程序,如下所示:
app.js
app.use(function(req,res,next){
req.db = db;
next();
});
app.get('/', routes.index);
app.get('/tasks', routes.getAllTasks);
Run Code Online (Sandbox Code Playgroud)
然后它应该可以在任何路线中使用req.db.
| 归档时间: |
|
| 查看次数: |
6655 次 |
| 最近记录: |