Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meteors collection cursor forEach not working

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);
    });
}
like image 491
stariqmi Avatar asked Apr 23 '13 01:04

stariqmi


1 Answers

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

like image 138
Josmar Avatar answered Nov 18 '22 05:11

Josmar