[SOLVED] Getting value on page returned from Aggregate


#1

I’ve added an aggregation to try and get a count from a subcollection, and it’s working, but when i try to put the count on the template, it’s not showing. Not sure where I’m going wrong.

<div class="col s6 countNumber">
            {{TotalGifts}}
</div>

Here’s my helper:

TotalGifts: function() {
    console.log("Total: ");
    Meteor.call('get.totalGifts', function(err, result){
        if (err) {
            console.log("Error: " + err);
        } else {
            var count = result[0].count;
            console.log(count);
            return count;
        }
    });
},

The console.log works just fine, and shows the correct count…

And, just so you have it, my Aggregation function run on the server.

'get.totalGifts' () {
    console.log("getting total gifts:");

    var totalGifts = Recipients.aggregate({ $unwind: "$gifts" }, { $group: { _id: '', count: { $sum: 1 }}});
    return totalGifts;

},

As always, any help is appreciated.


#2

You cant return a meteor method on helper like that. try this

yourtemplate.onCreated(function(){
  this.giftCount = new ReactiveVar(0); //define state with reactiveVar
  this.autorun(()=>{
       Meteor.call('get.totalGifts', function(err, result){
        if (err) {
            console.log("Error: " + err);
        } else {
            var count = result[0].count;
            console.log(count);
            this.giftCount.set(count); //set state after method return result
        }
    });
  });
});

yourtemplate.helpers({
   TotalGifts(){
     let instance = Template.instance();
     return instance.giftCount.get(); //get state
   }
});

or using Publish Count package


#3

You rock @mingliang7! That worked perfectly! Thank you so much for your help!


#4

You’re welcome @bmcgonag1