根据 startDate 对数组进行排序

Sort array based on startDate

我正在尝试对数组进行排序,但运气不佳。如果我删除 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

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

这个 returns 教育对象数组,按 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>