Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
483 views
in Technique[技术] by (71.8m points)

publish subscribe - Meteor collection fetch returns empty array but is subscribed

I uninstalled the autosubscribe and restarted the meteor app. Since then, I haven't been able to access my collection data on the client.

Every question related to the empty array return comes up with the same answer: the subscribed data isn't available yet. But no matter how long I wait I never see the data on the client.

Server:

Meteor.startup(function () {
  Meteor.publish("states", function () {
    return states.find();
  });
});

Logging states.find().fetch() on the server spits out my states as expected.

On the client:

Meteor.subscribe("states", function(){
  console.log(states, states.find(), states.find().fetch());
});

states and states.find() return objects as expected, .fetch() returns an [].

Waiting (even several minutes) then running states.find().fetch() in the browser console gives me [] still.

Thoughts?

EDIT

Collection is declared outside of the isServer/isClient blocks (to utilize schemas).

states = new Meteor.Collection("states");
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think you are getting [] because you are publishing the data on the startup, when isn't ready, lets make that subscribe reactive.

Tracker.autorun(function(){
   Meteor.subscribe("states", function(){
      console.log(states, states.find(), states.find().fetch());
   });
});

OPTIONAL

There is no reason to declare the collections inside the isServer/isClient if statements

Since you are starting with the Good practices (removing insecure/autopublish packages)

Lets do the follow.

First Create the folder structure. (check meteor/structuringyourapp and this SO).

Inside the appName/lib/collection.js put this code.

states = new Meteor.Collection("states");
//optional you can place this subscribe inside the appName/client/main.js
if(Meteor.isClient){
   Meteor.subscribe("states", function(){
      console.log(states, states.find(), states.find().fetch());
   });
}

and on the appName/server/publish.js

Meteor.publish("states", function () {
    return states.find();
  });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...