快速车把帮手无法正常工作

时间:2019-07-08 04:10:38

标签: javascript express handlebars.js express-handlebars

在我正在工作的node / express博客应用程序中,我使用express-handlebars包进行模板制作。

我的问题牵涉到我创建的帮助程序,以确定一个用户是否已经在关注另一个用户的博客。当userA访问userB的博客时,此帮助程序应触发并循环遍历userB的关注者(id#的数组),以查看userA的ID是否在该数组中。如果是这样,则会出现一个提醒,提示userA已经在关注此博客;如果没有,那么会有一个按钮邀请他们关注博客。

问题是此帮助程序没有捕获ID之间的匹配项。已经在关注博客的用户仍会获得按钮而不是提醒。

这是一些代码。首先,这是车把视图文件。第一个检查{{#if user}}是检查是否确实有一个登录用户,该用户来自passportjs。第二项检查确定已登录用户是否在自己的博客或其他用户的博客上。如果是他们自己的博客,那么关于关注的问题显然是无关紧要的。第三项检查是我们感兴趣的:

{{#if user}}
    {{#unequal account.username user.username account}}
            {{#following acc.followers ../user._id acc}}
            <div class="d-flex justify-content-around mt-2">
                <p id='alreadyFollowing' class="bg-primary text-white px-4 py-2 br-4">You are following {{../acc.username}}</p>
            </div>
            {{else}}
            <div class="d-flex justify-content-around mt-2">
                <form action="/account/addfan/{{../acc.username}}" method="post">
                    <button type="submit" id="fan" class="text-white btn bg-primary p-2"><i class="fa fa-users fa-lg">&nbsp; </i>Follow {{../acc.username}}</button>
                </form>
            </div>
            {{/following}}                
    {{/unequal}}
{{/if}}

{{#following}}助手执行检查:“ acc.followers”是指所访问博客(或帐户)的关注者的ID数组,user._id是来访用户的ID。如果返回true,则呈现提醒。如果没有,则显示按钮。

这是我定义并注册了助手的app.js文件:

app.engine('handlebars', exhbs({    
defaultLayout: 'blogview',
helpers: {

    unequal: (v1, v2, v3, options) => {
        if(v1 !== v2) { return options.fn({name1: v1, name2: v2, acc: v3}); }
        return options.inverse(this);
    },


    following: (arr, ID, acc, options) => {
        for(let i = 0; i < arr.length; i++) {
            console.log(arr[i]+' '+ID);
            if (arr[i]['_id'] === ID) { return options.fn({arr:arr, ID:ID, acc:acc}); }
            break;
        }
        return options.inverse(this);
    }
}    
}));

app.set('view engine', 'handlebars');

如果应该指出,辅助程序{{#unequal}}可以正常工作并且符合预期。辅助程序{{#following}}无效。我正在运行console.log以确保所有数据都存在。下面是一个示例,说明我从存储在mongoose / mongodb中的两个演示帐户中获取的信息:

{ _id: 5d181b52a8b40944b8d616ba } 5d181b52a8b40944b8d616ba
{ _id: 5d181b61a8b40944b8d616bc } 5d181b52a8b40944b8d616ba
{ _id: 5d196001494f7f155cf00901 } 5d181b52a8b40944b8d616ba
{ _id: 5d195fe8494f7f155cf008ff } 5d181b52a8b40944b8d616ba

因此,在这种情况下,userB具有四个关注者。在每次通过数组时,我们都有一个跟随userB的ID的日志,然后是访问用户userA的ID的日志。如您所见,userA的ID位于此数组的位置0,我认为应该返回true并呈现提醒消息。

但是,这再次没有发生。即使userA已经在关注该助手,它也会返回false并呈现邀请关注的按钮。

这是什么问题?我在快速车把中缺少助手吗?还是我在使用JavaScript时犯了一些愚蠢的错误?

任何帮助将不胜感激。预先感谢

0 个答案:

没有答案
相关问题