spjy
spjy

Reputation: 467

Meteor Mongo onRendered .count() incorrectly returning value

In Meteor, I'm trying to set a session variable in the onRendered template function. Specifically, I want to count the number of documents that are returned from the MongoDB collection by using Meteor.users.find({}).count() and storing it in the session variable:

admin.js

Template.admin.helpers({
    users() {
        var skip = Session.get('adminUserListPageCurrent');
        return Meteor.users.find({}, {limit: 1, skip: skip});
    },
    pages() {
        return Meteor.users.find({}).count();
    }
});

Template.admin.onRendered(function () {
    var users = Meteor.users.find({}).count();
    Session.set('adminUserNumberOfPages', users);
});

In total, there are three user accounts; however, it returns a value of zero in the onRendered template function. Contrarily, it correctly returns the value in my template helper.

Upvotes: 0

Views: 125

Answers (1)

JeremyK
JeremyK

Reputation: 3240

You need to wait until the data is available in the meteor.Users collection on the client. This code uses autorun to update your Session variable when the client receives the data, (and future updates). If you want this to just run once on startup, you could try using Meteor.setTimeout

Template.admin.onRendered(function () {
  console.log('Initially in onRendered: ', Meteor.users.find({}).count());

  this.autorun(() => {
    var users = Meteor.users.find({}).count();
    Session.set('adminUserNumberOfPages', users);
    console.log('In autorun: ', Meteor.users.find({}).count());
  });

});

Upvotes: 3

Related Questions