我最近开始使用Node.js + Express + MongoDB。 我设置了包含简单的应用程序:
/**
* Module dependencies.
*/
var express = require('express')
, routes = require('./routes')
, mongoose = require('mongoose')
, models = require('./models')
, Document
, db;
// lots of conf ...
models.defineModels(mongoose, function() {
app.Document = Document = mongoose.model('Document');
db = mongoose.connect(app.set('db-uri'));
})
// Routes
app.get('/', routes.home);
app.get('/documents.:format?', routes.list);
// classical end of app.js
我也有一个“路线”文件夹内的相应的“index.js”文件,其中包含:
exports.home = function(req, res){
res.render('index', { title: 'Indx' })
};
exports.list = function(req, res){
Document.find().all(function(documents) {
switch (req.params.format) {
case 'json':
res.send(documents.map(function(d) {
return d.__doc;
}));
break;
default:
res.render('index', { title: 'Indx' });
}
});
};
路由部分是确定的,意义当我将浏览器指向localhost:3000时,我看到(Jade-template generated)'index'视图。当我指向localhost:3000/documents时,路由工作正常,代码正在尝试为我的'index.js'路由的'list'部分提供服务。但是,我希望,我在主应用程序创建的“文档”猫鼬模型将“index.js”内的认可,但这显然并非如此,因为我不断收到以下错误:
Express
500 ReferenceError: Document is not defined
at C:\PERSO\DEV\indxjs\routes\index.js:23:2
at callbacks (C:\PERSO\DEV\indxjs\node_modules\express\lib\router\index.js:272:11)
at param (C:\PERSO\DEV\indxjs\node_modules\express\lib\router\index.js:246:11)
at param (C:\PERSO\DEV\indxjs\node_modules\express\lib\router\index.js:243:11)
at pass (C:\PERSO\DEV\indxjs\node_modules\express\lib\router\index.js:253:5)
at Router._dispatch (C:\PERSO\DEV\indxjs\node_modules\express\lib\router\index.js:280:4)
at Object.handle (C:\PERSO\DEV\indxjs\node_modules\express\lib\router\index.js:45:10)
at next (C:\PERSO\DEV\indxjs\node_modules\express\node_modules\connect\lib\http.js:204:15)
at Object.methodOverride [as handle] (C:\PERSO\DEV\indxjs\node_modules\express\node_modules\connect\lib\middleware\methodOverride.js:35:5)
at next (C:\PERSO\DEV\indxjs\node_modules\express\node_modules\connect\lib\http.js:204:15)
我能明显从“app.js”中定义的路由我喜欢的东西:
app.get('/documents.:format?', loadUser, function(req, res) {
// ...
}
但任何人都可以看到猫鼬交谈,而保留的优雅” ./routes/index.js'分离的方式'app.js'?
非常感谢
编辑:下面由韦斯样的回答,我下面的代码添加到“index.js”:
var Document;
function defineRoutes(mongoose, fn) {
Document = mongoose.model('Document');
fn();
}
exports.defineRoutes = defineRoutes;
// then the same as in initial post
我封闭函数中这个路由定义在“应用程序.js文件:
routes.defineRoutes(mongoose, function() {
app.get('/', routes.home);
app.get('/documents.:format?', routes.list);
})
一切正常,当我点为localhost:3000,但是当我点/文件,浏览器会将加载,加载...
请考虑将它作为解决问题的答案。 – rcdmk