3

Meteor リーダーボードに基づいた Meteor 投票プロジェクトをほぼ終了しましたが、少し問題があります。

私のDBの各アイテムには、投票で指定されたポイントを持つ配列があります。配列を合計し、結果をアプリに表示します。問題: ソートされていません。名前 (name = _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 に答える