Meteor: How can I tell when the database is ready?

后端 未结 6 940
醉话见心
醉话见心 2020-12-01 11:39

I want to perform a Meteor collection query as soon as possible after page-load. The first thing I tried was something like this:

Games = new Meteor.Collecti         


        
6条回答
  •  既然无缘
    2020-12-01 11:43

    You should first publish the data from the server.

    if(Meteor.isServer) {
        Meteor.publish('default_db_data', function(){
            return Games.find({});
        });
    }
    

    On the client, perform the collection queries only after the data have been loaded from the server. This can be done by using a reactive session inside the subscribe calls.

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

    Now when you perform collection queries, you can check if the data is loaded or not as:

    if(Session.get('data_loaded')){
         Games.find({});
    }
    

    Note: Remove autopublish package, it publishes all your data by default to the client and is poor practice.

    To remove it, execute $ meteor remove autopublish on every project from the root project directory.

提交回复
热议问题