Meteors collection cursor forEach not working

守給你的承諾、 提交于 2019-12-12 10:37:37

问题


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);
    });
}

回答1:


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



来源:https://stackoverflow.com/questions/16159533/meteors-collection-cursor-foreach-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!