jaggy
jaggy

Reputation: 822

Collections inside Meteor.call doesn't update server data

In my sever/publish.js, I have something like this:

Questions = new Meteor.Collection("questions");

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

In my client/app.js whenever I do something like this:

Questions = new Meteor.Collection("questions");

var questionHandle = Meteor.subscribe("questions");

Meteor.methods({
    post: function(title){
        Questions.insert({title: title});
    }
});

$('.save').on('click', function(){
    var title = $('input[name="title"]').val();
    Meteor.call('post', title);
});

It doesn't work! But if I put the code outside itself, the server data updates.

Questions = new Meteor.Collection("questions");

var questionHandle = Meteor.subscribe("questions");

$('.save').on('click', function(){
    var title = $('input[name="title"]').val();
    Questions.insert({title: title});
});

Is this a bug or am I missing something?

Upvotes: 2

Views: 691

Answers (1)

mquandalle
mquandalle

Reputation: 2598

Your method has to be defined on the server if you want to update the real server database. If you define it on the client as well it will be run first ("latency compensation)".

Questions = new Meteor.Collection("questions");

Meteor.methods({
    post: function(title){
        Questions.insert({title: title});
    }
});

if (Meteor.isServer){
  Meteor.publish("questions", function(){
      return Questions.find();
  });
}

if (Meteor.isClient){
  var questionHandle = Meteor.subscribe("questions");

  $('.save').on('click', function(){
      var title = $('input[name="title"]').val();
      Meteor.call('post', title);
  });
}

You can see the doc, and EventedMind screencast.

Upvotes: 5

Related Questions