Tarang
Tarang

Reputation: 75945

Meteor collection query 'undefined'

I have the code

datas = new Meteor.Collection("datas")
var data = datas.findOne('101abcde1f2345ac00000001')


if (Meteor.is_client) {
    Meteor.startup(function () {
        console.log(data.name)
    });
}

But what I get in the console is an undefined error. However if I type console.log(data.name) into the web inspector's javascript console (presumably after some kind of wait it works. I'm already putting the code in Meteor.startup to ensure that the DOM is ready. what could I be doing wrong?

Upvotes: 1

Views: 1448

Answers (1)

jifeng.yin
jifeng.yin

Reputation: 2151

It seems that you are using autopublish package. And (of course), Meteor.startup doesn't wait subscription completed.

Usually, we use reactive context & data to do this in Meteor -

datas = new Meteor.Collection("datas")

if (Meteor.is_client){
  Meteor.autosubscribe(function(){
    var data = datas.findOne('101abcde1f2345ac00000001');
    if (data){ console.log( data.name )}
  });
}

Anytime datas collection has changes(?), the function in Meteor.autosubscribe will be called.

Upvotes: 6

Related Questions