【问题标题】:How to sort and display mongo entries grouped by date in the meteor helpers / templates如何在流星助手/模板中排序和显示按日期分组的 mongo 条目
【发布时间】:2016-10-06 07:18:04
【问题描述】:

您好,抱歉我的英语不好。

我在 Paint 中画了一张图片,以便您更好地理解我的问题/意图: Sketch in Paint

我想在我的网站上构建这个 html 结构,如图所示。

我的mongodb结构:

{ "_id" : "doZfpnSFPzuPCi69W", "title" : "TodoA", "date" : "2016-10-03" }  
{ "_id" : "kLdCQotDBPmB3FGzY", "title" : "TodoB", "date" : "2016-10-03" }
{ "_id" : "fgAoaq53oNdKQSHXv", "title" : "TodoA", "date" : "2016-10-04" }
{ "_id" : "L6v4FC5PpyHjCkkpd", "title" : "TodoB", "date" : "2016-10-04" }

我知道如何用“每个”显示模板中的所有条目:

<template name="myTemplate">
  {{#each showTodos}}
  ...
 {{/each}}
</template>

但是,我不知道如何实现您在我的图片上看到的目的。我知道如何在流星中使用 if-else,但我不知道如何使用 if 语句来实现这个 html 结构。请你帮我写代码和逻辑好吗?

【问题讨论】:

    标签: mongodb meteor meteor-blaze


    【解决方案1】:

    您只需要嵌套两个{{#each}} 循环,一个用于日期,一个用于每个日期,所有匹配的文档。

    但首先您需要找到唯一的日期!为此,请使用下划线的 _.uniq() 函数。

    html:

    <template name="myTemplate">
      {{#each uniqueDates}}
        this
        {{#each todos}}
          ...
        {{/each}}
    </template>
    

    js:

    Template.myTemplate.helpers({
      uniqueDates(){
        const dates = myCollection.find({},{sort: {date: 1}})
          .map((doc)=>{return doc.date});
        return _.uniq(dates,true);
      },
      todos(){
        return myCollection.find({date: this});
      }
    };
    

    将.map() 应用于光标允许您仅将日期提取为数组。然后在数组上使用_.uniq() 来获取唯一值。 .uniq() 的第二个参数告诉它值已经排序。

    【讨论】:

      猜你喜欢
      • 2016-12-07
      • 2015-06-11
      • 2018-05-19
      • 2015-04-15
      • 1970-01-01
      • 2015-09-05
      • 1970-01-01
      • 2014-04-01
      • 2016-04-20
      相关资源
      最近更新 更多