Storing form information into a collection with the help of meteor methods

With Meteor, I am attempting to gather and store data (name, email, and age) using a form. This information should be saved in a new Meteor collection called "Subscribers". Below is my code:

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.');
            }
        }
    }
});

After entering data in the form and clicking the submit button, the success message appears in the console.log, confirming that the data was captured correctly. However, querying the collection does not display any results.

I have tried checking the collection using a template displaying the Subscribers table, Meteor Toys, and

console.log( Subscribers.find() );
, but no luck. It seems like the form submission works, but the data is not being saved in the collection.

https://i.sstatic.net/5q00N.jpg

Additionally, both autopublish and insecure have been removed.

https://i.sstatic.net/3cP8l.jpg

What could be the issue? As I am still new to Meteor, I may be overlooking something obvious here.

Please let me know if you require more code details. Feel free to provide any suggestions for code enhancement (structure or otherwise).

Thank you in advance!

Answer №1

Based on your question and subsequent comments, it appears that the Subscribers collection data is being successfully saved (as confirmed with meteor mongo), but you're experiencing difficulties retrieving the data using Subscribers.find(). With the removal of the autopublish package, ensure that you are subscribing to a publication responsible for transferring your Subscribers data from the server to the client. Here's an example:

/server/publications.js

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

/client/some_template.js

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

Once you have subscribed to the data, you can then execute Subscribers.find() on the client side to retrieve the data.

For further guidance, refer to the Publications and Data Loading section in the Meteor Guide.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

jQuery - Issue arises when no radio button is selected

Currently, I am working with a group of radio buttons and need to implement validation that shows an error message if none of the buttons are checked. Is there a method to retrieve the combined value of all radio buttons at once, or will I have to indivi ...

Ignore the certificate signature in Angular

Reviewing some older Angular code, I came across this: import { Headers, RequestOptions, Http, RequestOptionsArgs } from '@angular/http'; There is a function in the code: getInfo() { var info: RequestOptionsArgs = new RequestOptions({}); inf ...

Error message encountered when submitting a form after receiving an AJAX response: VerifyCsrfToken Exception

I'm encountering an issue with my AJAX functionality that involves rendering a form with multiple input fields and a submit button. Here is the AJAX call: <script type="text/javascript"> $('#call_filter').click(function() { $.aja ...

Separating buttons (two buttons switching on and off simultaneously) and displaying the corresponding button based on the data

My current project involves creating a registration page for specific courses. While I am able to display the information correctly, I am facing an issue with the ng-repeat function. The problem lies in all the Register buttons toggling incorrectly. Additi ...

Tips for aligning placeholder and text at the center in a React Material UI TextField

Existing Layout: https://i.stack.imgur.com/Zv4Tg.png Desired Layout: https://i.stack.imgur.com/Xuj6O.png The TextField element is displayed as follows: <TextField multiline={false} autoFocus placeholder={props.defaultAmt} ...

Preventing the browser from automatically sending AJAX requests

I'm currently using a web application created by my friend. The webpage is automatically making AJAX calls every 1 second, but I want to manually control when these calls are made using the Advanced Rest Client Application in Google Chrome extensions. ...

What is the best approach to determine the numerical equivalents of options in a dropdown menu using PHP and JS

Hey guys, I'm really stuck on this problem and I can't seem to find a helpful tutorial anywhere. I've got a form with two drop-down menus, each with a "value" attribute. What I want is for users to be able to select an item from both drop-do ...

Control the activation/deactivation of a dropdown menu depending on the selection of another dropdown menu

I need assistance with creating functionality for two dropdown lists. <select id="cat_user"> <option value="Super Admin">Super Admin</option> <option value="Event Admin">Event ...

Issue encountered while validating password using regex pattern?

There seems to be an issue with password validation when requiring 1 upper case, 1 lower case, 1 number, and 1 special character. methods: { validateBeforeSubmit() { this.$validator.localize('en', dict) this.$validator.validate ...

Ways to detect drag event on a CytoscapeJS node (specifically the one directly underneath the cursor/touch)

Currently, I am utilizing Cytoscape JS to develop a web browser-based tool for manipulating graphs. I am encountering an issue related to listening to the drag event of multiple selected nodes. I have successfully listened to the 'drag' event of ...

Unable to load module/controller file from Angular 1 into view/html

var app = angular.module("appModule",[]); app.controller("viewController",function($scope){ $scope.greeting = "Welcome to the future"; }); <html> <head> <script src="Scripts/script.js"></script> <script ...

When using the Vue Array.splice() method, the DOM element is not removed in the element-ui table

I am facing an issue with a table containing hierarchical data in Vue. When attempting to remove a child using "array.splice", the DOM structure does not update reactively. Has anyone encountered this before? Are there any potential solutions? This proble ...

Update the react component's state props to trigger a re-render when the state changes

I'm facing an issue with getting a component to rerender in React even though one of its components is a piece of state that receives updates. The piece of state in question is 'board': const [board, setBoard] = useState("") The component i ...

Utilizing a List<> as a template - asp.net mvc

When I return a view with a List as a model, the code looks like this: List<Indications.Analysis.PrepaymentResult> resultsList = Indications.Analysis.PrepaymentResult.GetPrepaymentResult(indication.Model.Trx, indication.Model.ShockBpsDropList.Value, ...

Adonis 5 and Vue encountering the error message 'E_ROUTE_NOT_FOUND'

I am currently working on a project using Adonis v5 as the backend and Vue 2 as the frontend. I have encountered an issue where, after building the Vue frontend into the public Adonis folder, accessing a specific route directly in the browser results in an ...

I am facing issues with installing React Router on my Windows device

After running the command to install react-router, this is the output from my prompt window: npm install --save react-router The prompt window shows several warnings and optional dependencies: npm WARN @babel/core requires a peer of @babel/core@^7.13 ...

Utilizing React Render Props to Pass References Between Components

Is there a way to access a ref that is passed between two external components using render props? I am trying to achieve something similar to this example usage. function Component() { // how can I retrieve the `ref` here? return ( <A> ...

originalRenderPage has not been declared

I encountered an issue while working on my new nextjs app. The problem arose when I tried to add a carousel using props in my project, resulting in an error stating that 'originalRenderPage' in Document.js is not defined. Any assistance would be ...

Revise the JSON format to be compatible with a JavaScript template library

My goal is to utilize JSON data for parsing a template using JavaScript. The Mustache library provides a solution as shown below: var output = $("#output"); // template stored in JS var as a string var templateString = '<div>'+ '< ...

Using the Chromecast SDK to stream content with m3u8 URLs

After setting up the webserver that is included in the SDK (https://github.com/googlecast/), I tested it with the provided example media file, which worked perfectly. However, when attempting to use an example m3u8 file, it resulted in the following error: ...