David
David

Reputation: 63

Fetch latest data on client side from server in meteor app

I have created a mongoDB collection through server code in meteor:

//Server
Restaurants = new Mongo.Collection('restaurants')   
if (Meteor.isServer) {
    //This code only runs on the server
    Meteor.publish('restaurants', function () {
    return Restaurants.find();
  }); 
}

I am trying to fetch latest data on client side every time when the data changes in the database.

This is my client side code:

//Client
Restaurants = new Mongo.Collection('restaurants');
var myData = "";

if (Meteor.isClient) {

    Meteor.subscribe('restaurants');        
    myData = Restaurants.find();
};  

Thanking you!

Upvotes: 0

Views: 297

Answers (1)

hwillson
hwillson

Reputation: 1399

For completeness, here's a quick revised example using your code that shows how Tracker works.

Restaurants = new Mongo.Collection('restaurants')

if (Meteor.isClient) {
  Meteor.subscribe('restaurants');
  Tracker.autorun(() => {
    const restaurant = Restaurants.findOne();
    console.log(restaurant);
  });
};

if (Meteor.isServer) {
  Meteor.publish('restaurants', function restaurants() {
    return Restaurants.find();
  });

  Meteor.startup(() => {
    if (Restaurants.find().count() === 0) {
      Restaurants.insert({
        name: 'McDonalds',
      });
    }
  });
}

The above will first log undefined to your console since when Restaurants.findOne is first called, no restaurant data has been pushed to the client yet. By wrapping your find in a Tracker.autorun, when restaurant data is pushed to the client, your find will re-run, and the loaded restaurant will be logged to the console. So your console output will look like:

undefined
Object {_id: "HAJpQxfq59KPmTwDA", name: "McDonalds"}

Upvotes: 1

Related Questions