【问题标题】:KeystoneJS middleware running twice when making a call to MongoDB using Model.find()使用 Model.find() 调用 MongoDB 时 KeystoneJS 中间件运行两次
【发布时间】:2018-01-07 07:46:47
【问题描述】:

我有一个加载公寓列表并显示它们的路线:

app.get( '/condo-list', middleware.loadCondoList, routes.views.condolist );

loadCondoList 中间件调用 CondoBuilding 模型并在 res.locals 上设置结果:

exports.loadCondoList = function loadCondoList( req, res, next ) {

console.log( 'request url: ' + req.url );
console.log( 'getting condo buildings...' );

CondoBuilding.model
    .find()
    .exec( ( err, condos ) => {
        if ( err ) {
            // pass error along
            next( err );
        } else {
            // add CondoBuildings to locals
            res.locals.condoBuildings = condos;
            next();
        }
    });
};

对数据库的调用成功,页面按预期呈现。但是,由于某种原因,该路线运行了两次。控制台输出如下:

request url: /condo-list
getting condo buildings...
GET /condo-list 304 344.532 ms
request url: /condo-list
getting condo buildings...
GET /condo-list 304 317.631 ms

我已经在多个浏览器(Chrome、Safari、Firefox)中重现了这种行为,并确认在任何其他路线上都不会发生这种情况。

如果我删除对CondoBuilding.model.find() 的调用,而只在loadCondoList() 的正文中调用next(),则不会发生此行为。

我正在运行 Keystone 4 "keystone": "4.0.0-beta.5",它利用 Express 4 "express": "4.14.0"

以下是我在应用程序中运行的路线的完整列表,以防相关:

// Setup Route Bindings
exports = module.exports = function ( app ) {

// Views
app.get( '/', routes.views.index );
app.get( '/condo-list', middleware.loadCondoList, routes.views.condolist );
app.get( '/blog/:category?', routes.views.blog );
app.get( '/blog/post/:post', routes.views.post );
app.get( '/about', routes.views.about );
app.get( '/search', middleware.getAccountType, routes.views.search );

app.all( '/contact', routes.views.contact );

};

CondoList 视图:

var keystone = require('keystone');

exports = module.exports = function (req, res) {

var view = new keystone.View(req, res);
var locals = res.locals;

// locals.section is used to set the currently selected
// item in the header navigation.
locals.section = 'condolist';

// Render the view
view.render('condolist');
};

我已经调试这个问题有一段时间了,但我不知道是什么原因造成的。任何帮助将不胜感激。

更新

我听从了@phuhgh 的建议,在 Express 调试模式下运行了应用程序。虽然我没有立即跳出来,但在应用程序启动期间我确实注意到了一些奇怪的事情。

下面是一系列正在准备的正常运行的路由:

express:router:layer new / +0ms
express:router:route new /blog/post/:post +0ms
express:router:layer new /blog/post/:post +0ms
express:router:route get /blog/post/:post +0ms
express:router:layer new / +0ms
express:router:route new /about +0ms
express:router:layer new /about +0ms
express:router:route get /about +0ms
express:router:layer new / +0ms
express:router:route new /search +1ms
express:router:layer new /search +0ms
express:router:route get /search +0ms

这是正在准备的公寓列表路线的顺序:

express:router:layer new / +0ms
express:router:route new /condo-list +0ms
express:router:layer new /condo-list +0ms
express:router:route get /condo-list +0ms
express:router:layer new / +0ms
express:router:route get /condo-list +0ms

您可能注意到,express:router:route get /condo-list +0ms 行重复了。我不知道为什么,但我假设这与我遇到的问题有关。我正在深入研究这个角度,但再次感谢在这方面有更多知识的人提供的任何帮助。

更新 2 - 堆栈跟踪

我已经调试并逐步完成了堆栈。我可以遵循从一个功能到另一个功能的路径,一切看起来都很正常,但我的正常基线是查看其他正常工作的路线。老实说,一旦我深入到 Express 的内心深处,我不知道该寻找什么。

我在遍历堆栈时所做的观察:

  • /condo-list 路由运行两次时的堆栈跟踪完全相同。
  • 堆栈跟踪(当然减去 loadCondoList 中间件)对于其他正常运行的路由(即仅一次)完全相同。
  • 如果我在另一个路由中添加对 loadCondoList 的调用,它也可以正常运行。
    • 例如我将/about 路由定义更新为:app.get( '/about', middleware.loadCondoList, routes.views.about );,它正确加载数据并且只运行一次。

在单步执行 Express lib 代码时,有什么需要特别注意的吗?我觉得那里有点超出我的深度,我不确定要寻找什么。

【问题讨论】:

  • 能贴出 routes.views.condolist 的代码吗?
  • CondoList 视图已添加 - 没有任何事情发生,因为所有加载都在中间件中处理。
  • 尝试启用快速调试模式,如此处所述expressjs.com/en/guide/debugging.html
  • 感谢@phuhgh - 我不知道那种模式,我会试一试!
  • 使用 findOne 而不是 find,这是有道理的,而且是一种好方法,因为您只对查找一条记录感兴趣,而在使用后一个。

标签: node.js mongodb express keystonejs


【解决方案1】:

经过几天的调试,我终于找到了罪魁祸首,它隐藏在最不可能的地方:视图!

上下文

视图加载了可以按社区过滤的公寓建筑的砖石显示。以下是砌体本身的相关 sn-p:

<!-- Condo List Masonry -->
<div class="condo-items">
{{#each condoBuildings}}
    <div class="condo-item {{neighborhood.key}}">
        <div class="condo-thumb">
            <span class="condo-tag tag-art">{{neighborhood.name}}</span>
            <a href="/{{condoUrl}}"><img src="{{{cloudinaryUrl image}}}" alt="{{name}}" /></a>
        </div>
        <div class="condo-body">
            <h3><a class="condo-name" href="#">{{name}}</a></h3>
            <p>{{condoDescription}}</p>
        </div>
    </div>
{{/each}}
</div>

问题是由这一行中的 cloudinaryUrl 助手引起的:

&lt;a href="/{{condoUrl}}"&gt;&lt;img src="{{{cloudinaryUrl image}}}" alt="{{name}}" /&gt;&lt;/a&gt;

这里是帮助代码:

_helpers.cloudinaryUrl = function (context, options) {

    // if we dont pass in a context and just kwargs
    // then `this` refers to our default scope block and kwargs
    // are stored in context.hash
    if (!options && context.hasOwnProperty('hash')) {
        // strategy is to place context kwargs into options
        options = context;
        // bind our default inherited scope into context
        context = this;
    }

    // safe guard to ensure context is never null
    context = context === null ? undefined : context;

    if ((context) && (context.public_id)) {
        options.hash.secure = keystone.get('cloudinary secure') || false;
        var imageName = context.public_id.concat('.', context.format);
        return cloudinary.url(imageName, options.hash);
    }
    else {
        return null;
    }
};

问题

某些 CondoBuilding 模型尚未定义 image。这会导致_helpers.cloudinaryUrl 方法中的context 参数为undefined。在这些情况下,助手将返回null。我仍然不确定为什么这会导致页面重新加载,但我确信这是罪魁祸首。

修复

更新 Handlebars 模板以仅在 CondoBuilding 模型上存在图像时呈现 &lt;img&gt; 元素。更新后的模板代码如下:

<!-- Condo List Masonry -->
<div class="condo-items">
{{#each condoBuildings}}
    <div class="condo-item {{neighborhood.key}}">
        <div class="condo-thumb">
            <span class="condo-tag tag-art">{{neighborhood.name}}</span>
            <a href="/{{condoUrl}}">{{#if image}}<img src="{{{cloudinaryUrl image}}}" alt="{{name}}" />{{/if}}</a>
        </div>
        <div class="condo-body">
            <h3><a class="condo-name" href="#">{{name}}</a></h3>
            <p>{{condoDescription}}</p>
        </div>
    </div>
{{/each}}

{{#if image}} 块添加到模板后,路由只运行一次,正如预期的那样!

后续步骤

对此实现的改进是为所有未定义 image 的 CondoBuildings 使用占位符图像。我将很快添加此功能,但我无法抗拒更新答案,因为我这几天一直在努力解决这个问题。

感谢大家的时间和关注。

【讨论】:

  • 很高兴你找到了它。 express:router:route get /condo-list 是调用 next() 时的问题,接下来的事情又是一样的(可能后面跟着一些 keystone 处理程序)。问题是第二次注册它到底是什么鬼?我猜是基石……不过,你必须得用快递来弄脏自己才能确定。 Express 的路由器非常简单,我很想在其中打一个断点并找出答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-07
  • 2021-03-04
  • 2017-09-24
  • 2021-04-27
  • 2022-11-12
  • 2015-11-03
  • 2017-11-20
相关资源
最近更新 更多