本文介绍了流星收集游标forEach不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么Meteor collection游标foreach循环不能在下面的代码中工作。如果我将循环包装在Template.messages.rendered或Deps.autorun函数中,它会工作。我不明白为什么。

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


解决方案

您的代码正在运行。



尝试这样:

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

其他解决方案:
$ b

只需使用订阅即可播放!您可以向订阅传递回调


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 subscriptionhttp://docs.meteor.com/#meteor_subscribe

这篇关于流星收集游标forEach不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 08:33
查看更多