使用 Model.find() 调用 MongoDB 时,KeystoneJS 中间件 运行 两次

KeystoneJS middleware running twice when making a call to MongoDB using Model.find()

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

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();
        }
    });
};

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

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(),则不会发生此行为。

我是 运行ning 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 的建议,运行 应用程序处于快速调试模式。虽然我没有立即想到什么,但在应用程序启动期间我确实注意到了一些东西 st运行ge 。

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

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,我就不知道该寻找什么了。

我在浏览堆栈时所做的观察:

在单步执行 Express 库代码时,有什么我应该特别注意的吗?我在那里感觉有点力不从心,我不确定要寻找什么。

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

上下文

该视图加载了可以按街区过滤的公寓建筑的砌体显示。以下是砌体本身的相关片段:

<!-- 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 助手引起的:

<a href="/{{condoUrl}}"><img src="{{{cloudinaryUrl image}}}" alt="{{name}}" /></a>

这是辅助代码:

_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。在这些情况下,助手将 return null。我仍然不确定为什么这会导致页面重新加载,但我确信这是罪魁祸首。

修复

如果 CondoBuilding 模型上存在图像,则更新 Handlebars 模板以仅呈现 <img> 元素。更新后的模板代码如下所示:

<!-- 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 的 CondoBuilding 使用占位符图像。我很快就会添加这个功能,但我忍不住更新了一个答案,因为我几天来一直在努力解决这个问题。

感谢大家的时间和关注。