node.js按类别排序数组并呈现它(切片)

时间:2018-04-22 10:22:53

标签: node.js

我正在学习节点,我已按类别进行排序并进行渲染,但我的计划是剪切文章。每个类别只应渲染其数组中的3个。我只是不知道如何做到这一点,我最后在一个循环中试图解决它。

我在app.js中的代码(因为它是一个主页)

app.get('/', function(req, res){
  Category.find({}, function(err, category) {
    Article.find({}, function(err, articles) { 
      res.render("index", { categories: category, articles: articles});
    });
  });
});

我的index.hbs(把手)

{{#each categories}}
    <div class="category">
        <a href="/category/{{this._id}}">{{this.title}}</a>
    </div> 
    {{#each ../articles}}
        {{#ifEquals ../this.title   this.category}}
            <div>{{this.title}}</div>   
        {{/ifEquals}}
    {{/each}}
{{/each}}

我已经注册了帮助切片,当我像这样使用它时它可以工作

{{#slice articles limit="3"}}
<div>{{this.title}}</div>
{{/slice}}

但如上所述,我想在每个类别中只提供3篇文章,但我不知道如何:/

1 个答案:

答案 0 :(得分:0)

然后问题似乎是你没有限制Article.find只返回articles category所以对于每个类别都会返回所有文章,所以结果是每个类别相同的3篇文章。 <{1}}上的{}查询需要包含Article.find

如果category是一个数组,那么你可以在传递它之前获取它的切片以进行渲染:

articles

这导致前3篇文章。索引0,1和2的那些。

articles = articles.slice(0, 3);