Meteor:如何判断数据库何时准备就绪?

Der*_*urn 14 meteor

我希望在页面加载后尽快执行Meteor集合查询.我尝试的第一件事是这样的:

Games = new Meteor.Collection("games");
if (Meteor.isClient) {
  Meteor.startup(function() {
    console.log(Games.findOne({}));
  }); 
}
Run Code Online (Sandbox Code Playgroud)

但这不起作用(它打印"undefined").从JavaScript控制台调用时,几秒钟后相同的查询工作.我假设在数据库准备好之前存在某种延迟.那么如何判断此查询何时成功呢?

OSX 10.8和Chrome 25下的Meteor版本0.5.7(7b1bf062b9).

soh*_*ifa 17

您应该首先publish从服务器获取数据.

if(Meteor.isServer) {
    Meteor.publish('default_db_data', function(){
        return Games.find({});
    });
}
Run Code Online (Sandbox Code Playgroud)

在客户端上,仅在从服务器加载数据后才执行收集查询.这可以通过在subscribe调用中使用被动会话来完成.

if (Meteor.isClient) {
  Meteor.startup(function() {
     Session.set('data_loaded', false); 
  }); 

  Meteor.subscribe('default_db_data', function(){
     //Set the reactive session as true to indicate that the data have been loaded
     Session.set('data_loaded', true); 
  });
}
Run Code Online (Sandbox Code Playgroud)

现在,当您执行集合查询时,您可以检查数据是否已加载:

if(Session.get('data_loaded')){
     Games.find({});
}
Run Code Online (Sandbox Code Playgroud)

注意:删除autopublish包,它默认将所有数据发布到客户端,这是不好的做法.

要删除它,请$ meteor remove autopublish从根项目目录执行每个项目.

  • 你有没有在这里使用订阅句柄和`ready()`方法的原因? (3认同)
  • 2015年更新:现在我们有[Template.instance().subscriptionsReady()](http://stackoverflow.com/questions/12879762/displaying-loader-while-meteor-collection-loads/12880255#12880255). (3认同)

Den*_*hev 8

使用DDP._allSubscriptionsReady()(流星0.7)

  • 2015年更新:现在我们有官方[Template.instance().subscriptionsReady()](http://stackoverflow.com/questions/12879762/displaying-loader-while-meteor-collection-loads/12880255#12880255). (4认同)

Dan*_*scu 6

从Meteor 1.0.4开始,有一个帮助器可以准确地告诉您特定订阅何时准备就绪:Template.instance().subscriptionsReady().

由于这个问题是重复的,请在原始问题中检查我的答案,在流星收集加载时显示加载器.