Node.js   发布时间:2022-04-24  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了node.js – 使用Model.find()调用MongoDB时运行两次的KeystoneJS中间件大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个加载公寓列表并显示它们的路线:

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',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');
};

我已经调试了这个问题一段时间,但我最终知道是什么导致了这个问题.任何帮助,将不胜感激.

updatE

我按照@ 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 – 堆栈跟踪

node.js – 使用Model.find()调用MongoDB时运行两次的KeystoneJS中间件

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

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

>堆栈跟踪与/ condo-list路由运行时完全相同.
>堆栈跟踪(当然减去loadCondoList中间件)对于正常运行的其他路由(即仅一次)完全相同.
>如果我在另一个路由中添加对loadCondoList的调用,它也可以正常运行.

>例如我将/ about路由定义更新为以下@L_772_15@:app.get(‘/ about’,routes.views.about);它正确加载数据,只运行一次.

当我踩过Express lib代码时,有什么我应该特别注意的吗?我感觉有点超出我的深度,我不知道该寻找什么.

解决方法

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

上下文

该视图加载了可以通过邻域过滤的公寓建筑的砖石显示.以下是砖石本身的相关片段:

<!-- 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模型尚未定义图像.这会导致_Helpers.cloudinaryUrl方法中的context参数未定义.在这些情况下,帮助程序将返回null.我仍然不确定为什么这会导致页面重新加载,但我确信这是罪魁祸首.

修复

更新Handlebars模板仅渲染< img>如果CondoBuilding模型上存在图像,则为element.更新的模板代码如下所示:

<!-- 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}}块,路由只运行一次,如预期的那样!

下一步

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

感谢大家的时间和关注.

大佬总结

以上是大佬教程为你收集整理的node.js – 使用Model.find()调用MongoDB时运行两次的KeystoneJS中间件全部内容,希望文章能够帮你解决node.js – 使用Model.find()调用MongoDB时运行两次的KeystoneJS中间件所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。