Search code examples
meteormeteor-autoform

Consider Publish/Subscribe rules outside of templates (Meteor)


I have an app where each User has a Counter object associated with it. The User is subscribed to the corresponding Counter.

Each time a user submits the form, I want to save the current value of the User's Counter to the form. However, the client and server disagree on what Counter object to use.

Counters = new Mongo.Collection("counters");
Router.route('/register', { name: 'insertRegistration',
    waitOn: function() {
      return [ Meteor.subscribe('counters') ];
    },
});
RegistrationSchema = new SimpleSchema({
    somevalue: {
        type: String,
        autoValue: function() {
            console.log(Counters.findOne()); // Different results on client and server
            return "whatever";
        }
    }
});
if (Meteor.isServer) {
    Meteor.publish('counters', function() { 
        return Counters.find({ user_id: this.userId });
    });
}

Counters.findOne() on the client picks the Counter object associated with the current user. Counters.findOne() on the server picks a Counter object out of the collection of all Counter objects.

I think this is because the Client asks for Counters and gets what it's subscribed to, while Server asks for Counters and gets the Collection.

Is there a way to consider the publish/subscribe rules on the server?


Solution

  • On the server, do

    Counter.findOne({ user_id: this.userId }) 
    

    to get the correct counter for the user.