sonlexqt
sonlexqt

Reputation: 6469

Meteor - How to know if a Meteor.Collection.find method is done?

I'm using Meteor to develop a small app. When I use this line of codes:

var currentTypingUsers = Utilites.findOne({title: "typingUsers"});

.. to get the currentTypingUsers value from the database, it always return undefined. So I guess the problem here is that the database is not ready yet. So I'm looking for a way to make a callback after Utilites.findOne({title: "typingUsers"}); has been called.

In mongodb they have a syntax like this: collection.find(query, callback); but it seems like Meteor.Collection doesn't support that syntax. And I'm still stucking at this.

So, can you guys help me with this, how to know if a Meteor.Collection.find method is done ? Thanks a lot in advanced !

Upvotes: 1

Views: 374

Answers (1)

shambles
shambles

Reputation: 666

You will get undefined when Meteor has not sent its initial payload of data from a publication to the client.

You can do the following:

utilitiesSub = Meteor.subscribe("utilities");

then use

if (utilitiesSub.ready()) { ... }

Probably in a Deps.autorun would be best.

So to clarify, assuming this is happening client side, it is not a case of it taking a while for a .find() to finish. It is the fact that the client hasn't received all of the collection data from the server yet and so the find (which actually happens client side, you can close the server and it will still work) has nothing to work with.

If this is causing errors in the initial stages of a template loading then I highly recommend using iron-router and its waitOn functions. It makes this a lot less painful.

Upvotes: 1

Related Questions