I create function to get staff collection by id like this:
// in client/...
getName= function (collection, id) {
var name = 'No Name';
var data = collection.findOne(id);
if(data != null){
name = data.name;
}
return name;
}
-----------------------------
// call function
Meteor.subscribe('staff');
alert(getName(StaffCollection, '001'));
---------------------------------
// Show "No Name" when click btn to the first time, but when i click btn the second time it can get data from the server.
That’s because the subscription isn’t ready at the time you call getName (the client hasn’t received the data from the server yet). This is a common beginner mistake, one of the similar questions is this one. In short, you can pass a function (a ready callback) to Meteor.subscribe that will get called when the subscription is ready (when the client has the data).
You can’t do anything like that, but what do you plan to do with the result? In Meteor, one usually use reactivity to “solve” this, but what it would look like depends on your use case. You mentioned a button in your question, so the result is going to be used in a template, or what?
It’s important to learn about publications and subscriptions – particularly, in this case, how subscriptions are asyncronous, but how you can also use reactivity to know when a subscription is ready (i.e. when the documents have all arrived on the client and are ready to be queried using Posts.find(), etc.).
In that case, you’re better of using a method call:
// On the server.
Meteor.methods({
getName: function(id){
var data = YOUR_COLLECTION.findOne(id);
if(data != null){
return data.name;
}
return "No name";
}
})
// On the client.
Meteor.call('getName', function(name){
YOUR_COLLECTION2.insert({
name: name
// And more...
})
})