【问题标题】:Node.js Express routing with MongoDB使用 MongoDB 的 Node.js Express 路由
【发布时间】:2012-06-08 16:21:47
【问题描述】:

下午好,

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

我在 'routes' 文件夹中也有一个对应的 '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 模板生成的)“索引”视图。当我指向 localhost:3000/documents 时,路由工作正常,并且代码正在尝试为我的“index.js”路由的“列表”部分提供服务。但是,我希望我在主应用程序中创建的“文档”猫鼬模型能够在“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) {
    // ...
}

但是任何人都可以看到一种与 mongoose 交谈的方式,同时保留优雅的 './routes/index.js' 与 'app.js' 的分离吗?

非常感谢

编辑:按照 Wes 的友好回答,我将以下代码添加到 'index.js':

var Document;
function defineRoutes(mongoose, fn) {
  Document = mongoose.model('Document');
  fn();
}
exports.defineRoutes = defineRoutes;
// then the same as in initial post

我在 'app.js' 中包含了这个函数中的路由定义:

routes.defineRoutes(mongoose, function() {
  app.get('/', routes.home);
  app.get('/documents.:format?', routes.list);
})

当我指向 localhost:3000 时一切正常,但是当我指向 /documents 时,浏览器一直在加载、加载……

【问题讨论】:

    标签: node.js routing express mongoose


    【解决方案1】:

    感谢 Wes Johnson,我找到了出路。我盲目地遵循一个过时的教程,它使用了 MongoDb 中已弃用的方法。下面是我最后用来实现“列出文档”功能的代码sn-p:

    exports.list = function(req, res){
        Document.find({},function(err, documents) {
            switch (req.params.format) {
                case 'json':
                    res.send(documents.map(function(d) {
                        return d.toObject();
                    }));
                break;
                default:
                    res.render('index', { title: 'Indx' });
            }
        });
    };
    

    再次感谢韦斯!

    【讨论】:

    • 如果它解决了您的问题,请考虑将其作为答案。
    【解决方案2】:

    节点模块在变量范围方面是自包含的。正如您所提到的,您的 Document 对象无法从 index.js 访问。您需要将其传递给您的路由逻辑,或传递 mongoose 本身。

    require 调用大部分都被缓存,因此需要在您的index.js 文件中使用猫鼬并获取Document 的实例,这是一种选择。

    由于您并没有真正在 app.js 中使用 Document,因此您可以随时将 db 配置移动到另一个模块并将重要的引用导出回需要它们的脚本。

    【讨论】:

    • 感谢您的回答,我按照我的尝试编辑了问题,但没有运气......
    • 所以您不再收到Document is not defined 错误了吗?你不应该。如果页面永远不会加载,您就永远不会达到响应流线。乍一看,您的数据库调用可能有问题。我从未见过以这种方式使用.all...here's what it's supposed to do。如果您想获取所有文档,只需使用find
    猜你喜欢
    • 2020-05-14
    • 1970-01-01
    • 2015-01-30
    • 2017-04-14
    • 2019-09-02
    • 2015-01-03
    • 2018-09-10
    • 2013-08-27
    • 1970-01-01
    相关资源
    最近更新 更多