Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meteor.js Collection empty on Client

Why is it that myCollection.find().fetch() returns an empty array [] even though the call is made within if(data){...}? Doesn't the if statement ensure that the collection has been retrieved before executing the console.log()?

Template.chart.rendered = function() {

        var data = myCollection.find().fetch();

        if(data) {
            console.log(data);
        }

        $('#chart').render();

}

This returns [] in the browser Javascript console.

like image 800
Nyxynyx Avatar asked Nov 26 '13 05:11

Nyxynyx


Video Answer


2 Answers

You could use count() instead which returns the number of results. data itself would be an empty array, [] which isn't falsey ( [] == true ).

Also don't use fetch() unless you're going to use the raw data for it because its quite taxing. You can loop through it with .forEach if you need to.

var data = myCollection.find();

if(data.count())
  console.log(data);

//If you need it for something/Not sure if this is right but just an example
$('#chart').render(data.fetch())
like image 113
Tarang Avatar answered Oct 20 '22 08:10

Tarang


The problem is that you have to wait for data from the server. When you just use Template.name.rendered function it is immediately invoked. You have to use Template.name.helpers function to wait for data from the server. Everything is described in the documentation.

like image 31
Łukasz Jagodziński Avatar answered Oct 20 '22 09:10

Łukasz Jagodziński