【问题标题】:Meteor Aggregated result not showing in template流星聚合结果未显示在模板中
【发布时间】:2015-12-22 04:43:49
【问题描述】:

我正在关注这个answer on stackoverflow。在控制台中,我得到了正确的总和。

Meteor.publish('hoursTotal', function() {
    var self = this;
    var pipeline = [
        {$group: {_id: "$userId", hours: {$sum: "$hours" }}}
    ];
    var result = Reports.aggregate(pipeline);

    _.each(result, function(result) {
        self.added("hoursTotalSum", result._id, {
            userId: result._id,
            hours: result.hours
        });
    });
    console.log(result);
    self.ready();
});

我已经订阅了在客户端创建的新集合:

Meteor.subscribe('hoursTotalSum');

我的模板助手:

Template.statsBrief.helpers({
    hoursTotalSum: function() {
        var currentUserId = Meteor.userId();
        return Reports.find({userId: currentUserId});
    },
});

我的模板:

{{#each hoursTotalSum}} {{hours}} {{/each}}

Meteor 控制台返回这个:

[ { _id: 'F8ZEWeKMoRfXaEGNa', hours: 30 },
I20151221-09:57:09.097(0)?   { _id: 'ufALZHfhWyQ8pMkgD', hours: 85 } ]

Meteor 模板返回:

50 20 15

虽然求和正确,并且后端控制台确认了这一点,但我仍在努力将值放入模板中。

【问题讨论】:

    标签: meteor


    【解决方案1】:

    我通过meteorhacks:aggregate 包成功使用了聚合,但是我的做法与您的示例有所不同。我将展示如何实现相同的目标,而不是调试您的代码。

    注意 :以下代码在coffeescript中

    编写流星方法

    创建一个服务器端 Meteor 方法来执行聚合。您不需要 publish 聚合,因为所有处理都发生在服务器上,结果由您通过 $project 步骤控制。

    Meteor.methods 
        getHoursTotal: ->
            return null unless @userId
            check @userId, String
            pipeline = [
                {$group:{'_id': @userId, 'hours':{$sum:'$hours'}}},
                {$project: 
                    _id:false, 
                    userId:'$_id', 
                    hours: '$hours', 
                }
            ]
            return reports.aggregate pipeline
    

    在您的代码中,您正在处理结果中的每个项目。看起来您只是想将 _id 重命名为 userId 并包含计算得出的 hours 字段。我是在$project 步骤中执行此操作的。

    调用 Meteor 方法

    您的代码依赖于可用的userId,因此我们只想在用户登录后运行它。我们可以使用tracker 使其反应。

    Tracker.autorun ->
        return unless Meteor.userId()?
        Meteor.call 'getHoursTotal', (err, res) ->
            Session.set 'hoursTotal', res
    

    现在代码只会在Meteor.userId 不为空时进行调整,并且当它运行时hoursTotal 将存储在Session 中以供使用。

    公开结果

    为了很好地展示结果,最好将其放在模板助手中。

    Template.statsBrief.helpers
        hoursTotal: -> Session.get 'hoursTotal'
    

    我认为以这种方式执行聚合和显示结果更简单,同时也受益于完全反应式。

    【讨论】:

    • 您的解决方案运行良好,reative 等等,但我似乎仍然无法在模板中访问。我可以在客户端的控制台中Session.get('hoursTotal'),但在模板中,我很挣扎
    • 好的,想通了。 res 对象包含0 的索引,因此我只是做了Session.set('hoursTotal', res[0]); 这您的方法更具反应性和趣味性。虽然我也可以使用其他方法,但我认为我更喜欢这种方法而不是前者
    猜你喜欢
    • 2018-06-01
    • 2015-04-21
    • 1970-01-01
    • 2013-08-08
    • 1970-01-01
    • 1970-01-01
    • 2016-10-07
    • 1970-01-01
    • 2014-04-01
    相关资源
    最近更新 更多