Meteor Mongo onRendered .count() 返回值不正确

Meteor Mongo onRendered .count() incorrectly returning value

在 Meteor 中,我试图在 onRendered 模板函数中设置一个会话变量。具体来说,我想使用 Meteor.users.find({}).count() 计算从 MongoDB 集合返回的文档数并将其存储在会话变量中:

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);
});

总共有三个用户帐户;但是,它 returns 在 onRendered 模板函数中的值为零。相反,它正确 returns 我的模板助手中的值。

您需要等到数据在客户端的 meteor.Users 集合中可用。此代码使用 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());
  });

});