基于startDate对数组进行排序

时间:2016-03-18 05:22:18

标签: meteor meteor-autoform

我正在尝试对数组进行排序而没有太多运气。如果我删除helper我打印出他们进入数据库的顺序中的所有资格。我想根据startDate按时间顺序显示它们。

路径:dbExample

"profile": {
    "CV": {
      "education": [
        {
          "qualification": "Arts Degree",
          "startDate": "2009-01-01T00:00:00.000Z",
          "endDate": "2013-12-01T00:00:00.000Z"
        },
        {
          "qualification": "Science Degree",
          "startDate": "2007-01-01T00:00:00.000Z",
          "endDate": "2008-12-01T00:00:00.000Z"
        }
      ]
    }
}

路径:education.html

<template name="education">
    {{#each educationHistory}}
    <div class="box">
        <p class="title">{{qualification}}</p>
        <p class="dates">{{startDate}} - {{endDate}}</p>                
    </div>
    {{/each}}
</template>

路径:education.js

Template.education.helpers({
    educationHistory: function () {
        return Meteor.users.find({}, {sort: {"startDate": 1}});     
    }
});

路径:Schema.js

Schema.Education = new SimpleSchema({
    qualification: {
        type: String,  
        optional: true    
    },
    startDate: {
        type: Date,  
        optional: true 
    },
    endDate: {
        type: Date,  
        optional: true  
    }
});

Schema.CV = new SimpleSchema({
    education: {
        type: [Schema.Education],
        optional: true
    }
});

1 个答案:

答案 0 :(得分:2)

这有点难以理解,因为我不知道模板的背景或用户的教育历史。以下是一些解决方案的想法:

解决方案1 ​​

Template.education.helpers({
  educationHistory: function () {
    // replace Meteor.user() with Meteor.users.findOne(someId) or something
    const { education } = Meteor.user().profile.CV;
    return _.sortBy(education, e => e.startDate);
  },
});

这将返回一个教育对象数组,按startDate排序。

解决方案2

如果模板已经有educationHistory没有帮助者(根据您在下面的评论),那么您可以用这个替换educationHistory帮助:

Template.education.helpers({
  sortByStartDate: function (education) {
    return _.sortBy(education, e => e.startDate);
  },
});

然后在你的模板中:

<template name="education">
  {{#each sortByStartDate educationHistory}}
    <div class="box">
      <p class="title">{{qualification}}</p>
      <p class="dates">{{startDate}} - {{endDate}}</p>
    </div>
  {{/each}}
</template>