1

Just trying to figure things out in Meteor JS. I am stuck trying to get a Meteor.call result object passed back into a template. Here is my code:

HTML Template

<template name="showTotals">
    <div class="container">
        {{#each recordCnt}}
        {{/each}}
    </div>
</template>

Client JS

//get a count per item
Template.showTotals.recordCnt = function(){

    Meteor.call('getCounts', function(err, result) {
    if (result) {
        //console.log(result); <-this shows object in javascript console
        return result;
        }
        else {
            console.log("blaaaa");
        }
    });

}

Server JS

Meteor.startup(function () {

    Meteor.methods({

      getCounts: function() {
        var pipeline = [{$group: {_id: null, count: {$sum : 1}}}];
        count_results = MyCollection.aggregate(pipeline);
        return count_results;
      }
    });
  });

Global JS

MyCollection = new Meteor.Collection('folks'); 

I have tried adding a console.log(result) for the results of the call, and it displays in the javascript console with the expected results. I cannot get this to populate recordCnt however.

Any ideas?

Bubee
  • 13
  • 4

1 Answers1

-1

You can't do it the way you want because the callback from the Meteor.call runs asynchronously.

You can, however, use the callback to set a Session value and have your helper read Session.get() instead.

Template.showTotals.rcdCount = function() {
  return Session.get('rcdCount');
}

Template.showTotals.rendered = function() {
  Meteor.call('getCounts', function(err, result) {
    if (result) {
        Session.set('rcdCount', result);
        }
        else {
            console.log("blaaaa");
        }
    });
}

See here for a similar answer that includes an example of a "hacky" way of doing it.

Community
  • 1
  • 1
RevMen
  • 562
  • 3
  • 14
  • 1
    `Template.showTotals.rcdCount = function() {}` delcairng helpers like that is to way old – Ethaan Apr 10 '15 at 18:05
  • This worked. Are sessions ok for limited for large data sets? What would happen if I were trying to pull 500 records, etc? – Bubee Apr 10 '15 at 18:21
  • Look into doing that with a custom publication. `Meteor.publish` can do more than just publish a cursor. Look [here](http://stackoverflow.com/questions/10565654/how-does-the-messages-count-example-in-meteor-docs-work) for a very detailed example. This may be a better way to accomplish what you're trying to do in your question. – RevMen Apr 10 '15 at 18:28