Khacho
Khacho

Reputation: 301

Meteor local server can access database but client can't

I'm new to meteor. So I want to access data from my local database in mongodb. I have client.js in client folder

Meteor.subscribe('Signal');
console.log(Data.find().fetch());

And my server directory has main.js having

console.log(Data.find());

Meteor.publish('Signal', function() {
   return Data.find().fetch();
});

Server's console.log shows result in the terminal but the client doesn't show anything the chrome's console

Under lib/ I have collectons.js it contains

Data = new Mongo.Collection('data');

I have checked my mongodb from shell and the collection data is present with needed data. What am I doing wrong?

Upvotes: 1

Views: 96

Answers (1)

Styx
Styx

Reputation: 10076

You're forgetting that Meteor.subscribe() on client is not immediate action, and publication will take its time to populate documents to client.

Fortunately, Meteor.subscribe() returns a subscription handle, that can be used to determine subscription readiness.

const handle = Meteor.subscribe('Signal');
Tracker.autorun(() => {
  if (handle.ready()) {
    // subscription is ready
    console.log(Data.find().fetch());
  }
});

Alternatively, you can pass your onReady callback as the last argument to Meteor.subscribe():

Meteor.subscribe('Signal', () => {
  // subscription is ready
  console.log(Data.find().fetch());
});

Upvotes: 1

Related Questions