我最近開始使用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