Adrian
Adrian

Reputation: 355

Save form data to collection using meteor methods

Using Meteor I'm trying to capture and save some data (name, email and age) using a form. This data should be saved in a new Meteor collection "Subscribers". My code as follows:

Template Events (client\views\subscribe_form\subscribe_form.js)

Template.Subscribe.events({ 
    'submit form#subscribe-form': function(event){
        // Prevent default browser form submit
        event.preventDefault();

        // Get values from the form
        var subName = $('form#subscribe-form [name=subscribe-name]').val();
        var subEmail = $('form#subscribe-form [name=subscribe-email]').val();
        var subAge = $('form#subscribe-form [name=subscribe-age]').val();

        let subscriberData = {
            name: subName,
            email: subEmail,
            age: subAge,
            createdAt: new Date()
        };

        // Insert subscriber into the collection
        Meteor.call('SubscribeNow', subscriberData, function(error, result){
            if(error){
                // Output error if subscription fails
                console.log(error.reason);
            } else {
                // Success
                console.log("Subscription successful");
                console.log(subscriberData);
                console.log( Subscribers.find() );
            }
        });
    },
});

Server side (server\collections\subscribers.js)

var Subscribers = new Meteor.Collection('subscribers');

Subscribers.allow({
    insert: function(){
        return true;
    }
});

Meteor.methods({
    'SubscribeNow': function (subscriberData) {
        //check(subscriberData, String);

        try {
            // Any security checks, such as logged-in user, validating data, etc.
            Subscribers.insert(subscriberData);
        } catch (error) {
            // error handling, just throw an error from here and handle it on client
            if (badThing) {
                throw new Meteor.Error('bad-thing', 'A bad thing happened.');
            }
        }
    }
});

Now when I add some data to the form and click the submit button it goes through the success console.log message, the data is picked-up properly but whenever I try to query the collection it won't show anything at all.

I tried looking for the data in the collection using a simple template I created to list the Subscribers collection in a table, also with Meteor Toys and via console.log( Subscribers.find() ); but no luck. It seems the forms goes through but the data is not saved in the collection.

enter image description here

Also, autopublish and insecure are removed.

enter image description here

What am I doing wrong? I'm still pretty new to everything Meteor so it might be something obvious I'm missing here.

Let me know if you need to see more of the code. Finally, any suggestions for code improvement (structuring or such) are welcome.

Many thanks in advance!

Upvotes: 0

Views: 1388

Answers (1)

hwillson
hwillson

Reputation: 1399

So from your question and comments you've added to your question, the Subscribers collection data is being saved properly (you've verified this using meteor mongo), but you can't retrieve the data using Subscribers.find(). Since you've removed the autopublish package, you'll have to make sure you're subscribing to a publication that's responsible for pushing your Subscribers data from the server to the client. For example:

/server/publications.js

Meteor.publish('allSubscribers', function () {
  return Subscribers.find();
});

/client/some_template.js

Template.someTemplate.onCreated(function () {
  this.subscribe('allSubscribers');
});
...

After you've subscribed to your data, you can then run Subscribers.find() client side, and have data returned.

For more information, see the Publications and Data Loading section of the Meteor Guide.

Upvotes: 1

Related Questions