【问题标题】:Meteor Mongo onRendered .count() incorrectly returning valueMeteor Mongo onRendered .count() 错误地返回值
【发布时间】:2017-06-15 02:18:48
【问题描述】:

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

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

【问题讨论】:

  • 此代码在客户端运行。当你的 onRendered 函数执行时,Meteor.users miniMongo 集合中有 0 个文档,因为它还没有收到来自服务器的数据。
  • 请注意,不需要从游标计数创建 Session 变量,因为Meteor.users.find({}).count() 本身就是一个反应性数据源,并且会自动更新任何依赖项。您看到不同的值仅仅是因为您第一次询问时订阅还没有准备好。

标签: meteor meteor-blaze


【解决方案1】:

您需要等到客户端上的meteor.Users 集合中的数据可用。此代码使用autorun 在客户端收到数据(以及未来更新)时更新您的 Session 变量。如果您希望它只在启动时运行一次,您可以尝试使用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());
  });

});

【讨论】:

  • 请注意其他阅读答案的人:注意 this.autorun() 中的函数将在 Meteor.users 集合中的数据发生变化时运行,因此它可能是 0、1、2、3,或者可能是 0、3(取决于数据传入的速度)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-15
  • 1970-01-01
  • 1970-01-01
  • 2020-05-02
  • 1970-01-01
  • 2015-06-22
  • 2015-04-11
相关资源
最近更新 更多