3

我几乎完成了基于 Meteor 排行榜的流星投票项目,但我有一个小问题。

我的数据库中的每个项目都有一个数组,其中包含投票时的给定点。我对数组求和并在我的应用程序中显示结果。问题:未排序,仅按名称排序(名称 = _id)。

HTML:

<template name="voting">
    {{#each books}}
        {{> book}} 
    {{/each}}
</template>
<template name="book">
    <div class="book {{selected}}">
        <span class="name">{{_id}}</span>
        <span class="totalscore">{{totalscore}}</span>
    </div>
</template>

JS

Template.voting.books = function () {
    return Books.find({flag: "score20130901"}, {sort: {totalscore: -1, _id: 1}});
};  

Template.book.totalscore = function () {
    var total = 0;
    for (var i=0; i<6; i++) {
        total += this.score20130901[i];
    }
    return total;
};

DB(文档示例)

{
    _id: "Dancing Joe",
    flag: "score20130901",
    score20130714: [0,0,8,0,0],
    score20130901: [0,4,0,5,0]
}
4

1 回答 1

2

我想我明白。试试这个(Underscore.js是我们的朋友):

Template.voting.books = function () {
    // First, get the books as an array
    var books = Books.find({flag: "score20130901"}).fetch();
    // Next, loop through the books, using underscore's sortBy method
    return _.sortBy(books, function (book) {
        // For each book, the number it should sort by is the sum of numbers in the score array
        return _.reduce(book.score20130901, function (memo, num) {
            return memo + num;
        });
    }).reverse(); // reverse() here for descending order
}; 
于 2013-08-27T16:00:24.183 回答