Why does the Meteor collection cursors foreach loop not work in the code below. If I wrap the loop inside a Template.messages.rendered or Deps.autorun function, it works. I dont understand why.
Messages = new Meteor.Collection("messages");
processed_data = [];
if(Meteor.isClient) {
data = Messages.find({}, { sort: { time: 1 }});
data.forEach(function(row) {
console.log(row.name)
processed_data.push(row.name);
});
}
Messages collection is not ready when your code is running.
Try something like this:
Messages = new Meteor.Collection("messages");
if(Meteor.isClient) {
processed_data = [];
Deps.autorun(function (c) {
console.log('run');
var cursor = Messages.find({}, { sort: { time: 1 }});
if (!cursor.count()) return;
cursor.forEach(function (row) {
console.log(row.name);
processed_data.push(row.name);
});
c.stop();
});
}
Other Solution:
Just play with subscriptions! You can pass a onReady callback to a subscription http://docs.meteor.com/#meteor_subscribe
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With