如何对嵌入式文档进行排序?

丹尼尔·菲舍尔(Daniel Fischer)

有什么方法可以根据contentItems对文档进行排序吗?

我正在渲染每个内容项,例如:

      {{#each contentItems}}
        {{> someTemplate}}
      {{/each}}

我想渲染每个按负载位置排序的对象。有什么办法可以对嵌入式文档(contentItems)执行此操作?

{
    "_id" : "sYKXwp27o2MCBtPsN",
    "contentItems" : [
        {
            "_id" : "NwsWpu3dqj7jByLkq",
            "position" : 0.75,
            "title" : "Nested animations in AngularJS using ui-router"
        },
        {
            "_id" : "Rve9R5uJzvrbgfrrX",
            "title" : "AngularJS Data Models: $http VS $resource VS Restangular",
            "position" : 1
        },
        {
            "_id" : "BNq9Fe9gdYJ6Wgoym",
            "position" : 0.875,
            "title" : "Random title? Nope it's static."
        }
    ],
    "title" : "Some title"
}

需要说明的是:我希望能够按位置值对contentItems进行排序,而不是按文档本身的顺序进行排序。这可能吗?

戴维·韦尔顿

您可以遍历对它们进行排序的帮助程序的结果。例如:

{{#each sortedContentItems}}
  {{> someTemplate}}
{{/each}}

其中sortedContentItems的样子:

Template.myTemplate.helpers({
  sortedContentItems: function() {
    return _.sortBy(this.contentItems, 'position');
  }
});

如果您希望将排序反向,则可以执行以下操作:

Template.myTemplate.helpers({
  sortedContentItems: function() {
    return _.sortBy(this.contentItems, function(ci) {
      return -ci.position;
    });
  }
});

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章