Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
331 views
in Technique[技术] by (71.8m points)

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

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.Collection("games");
if (Meteor.isClient) {
  Meteor.startup(function() {
    console.log(Games.findOne({}));
  }); 
}

This doesn't work, though (it prints "undefined"). The same query works a few seconds later when invoked from the JavaScript console. I assume there's some kind of lag before the database is ready. So how can I tell when this query will succeed?

Meteor version 0.5.7 (7b1bf062b9) under OSX 10.8 and Chrome 25.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...