Collect email addresses for all individuals in the array using Meteor

I am currently working on a project where I need to send emails to every individual in an array. To achieve this, I require the email address of each person. I have a collection called Benutzer/benutzer which includes the name and email address of each person.

Below is the code snippet from the client side:

Template.NeuesEvent.onCreated(function() {
    this.subscribe('events');
    this.subscribe('friends');
    this.subscribe('benutzer');
});

Template.NeuesEvent.events({
    "submit .add-event": function(event){
        var Name = event.target.name.value;
        var Beschreibung = event.target.beschreibung.value;
        var Datum = event.target.Datum.value;
        var Autor = Meteor.userId();
        var eingeladene = []; <-- this is the array
             $.each($('.FreundeCheckbox:checked'), function(){            
                eingeladene.push($(this).val());
            });

       var email = Meteor.Benutzer.findOne({"email": eingeladene});<<------

       <<---- here i want to grab the email adress 


        if (Name == "")
        {
            confirm("Das Event braucht einen Namen ;)")
        }
        else {

        Meteor.call('addEvent', Name, Beschreibung, Datum, eingeladene, Autor, email) <<--
<<------and paste the information here

        event.target.name.value = "";
        event.target.beschreibung.value = "";
        FlowRouter.go('/meineEvents');

        return false;
    }
    }
}); 

This part of my method.js does not contain the email function yet, but I am aware of how to implement it:

Meteor.methods({
    addEvent(Name, Beschreibung, Datum, eingeladene, Autor, email) {
         Events.insert({
            Name: Name,
            Beschreibung: Beschreibung,
            erstelltAm: new Date(),
            Datum: Datum,
            Eingeladen: eingeladene,
            Autor: Autor
        });

SSR.compileTemplate('InviteEmail', Assets.getText('Invite-Email.html'));
        var emailData = {
            Name: Name,
            Beschreibung: Beschreibung,
            erstelltAm: new Date(),
            Datum: Datum,
            Eingeladen: eingeladene,
            Autor: Autor
        };

    Email.send({
        to: email, <<<-----everytime a new one 
        from: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="117469707c617d7451747c70787d3f727e7c">[email protected]</a>",
        subject: "Einladung",
        html: SSR.render('InviteEmail', emailData),
      });
        }
    });

Now that you understand my objective, please assist me with two challenges - obtaining the email addresses and iterating over the `Email.send` function for each email address.

Answer №1

Kindly refrain from inserting comments into the code without providing meaningful explanations:

Incorrect Usage of Commenting:

var invited = []; <-- this is the array

Improved Approach:

var invited = []; // <-- this is the array

It's important to note that 'invited' is an array, therefore this line does not return anything:

var email = Meteor.Users.findOne({"email": invited});

The correct method would be:

var email = Meteor.Users.findOne({"email": {$in: invited}});

Alternatively, send an array of emails to the function and handle operations there. Here is an example:

Template.NewEvent.events({
    "submit .add-event": function(event){
        var Name = event.target.name.value;
        var Description = event.target.description.value;
        var Date = event.target.Date.value;
        var Author = Meteor.userId();
        var invited = []; 
         $.each($('.FriendsCheckbox:checked'), function(){            
            invited.push($(this).val());
        });

        // Email retrieval is unnecessary at this stage

        if (Name == "")
        {
            confirm("The event needs a name ;)")
        }
        else {

        // Removed Author and email as they are not required here
        Meteor.call('addEvent', Name, Description, Date, invited);

        event.target.name.value = "";
        event.target.description.value = "";
        FlowRouter.go('/myEvents');

        return false;
    }
    }
}); 

Meteor.methods({
    'addEvent': function(Name, Description, Date, invited) {
        this.unblock();
        var Author = Meteor.users.findOne(this.userId);

         Events.insert({
            Name: Name,
            Description: Description,
            createdOn: new Date(),
            Date: Date,
            Invited: invited,
            Author: Author
        });

        SSR.compileTemplate('InviteEmail', Assets.getText('Invite-Email.html'));
        var emailData = {
            Name: Name,
            Description: Description,
            createdOn: new Date(),
            Date: Date,
            Invited: invited,
            Author: Author
        };

        // Determine if fetching emails from the collection is necessary

        for (var i in invited) {
            var email = Meteor.Users.findOne({"email": invited[i]});
            if (!email) {
                continue;
            }


            Email.send({
                to: email, <<<-----everytime a new one 
                from: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fe9b869f938e929bbe9b939f9792d09d9193">[email protected]</a>",
                subject: "Invitation",
                html: SSR.render('InviteEmail', emailData),
            });
        }
    }
});

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

Creating PDFs with Rotativa that feature C3JS charts in an Asp.net environment

Currently, I am working on incorporating dashboard stats into one of my projects. I have successfully added charts to the dashboard using C3js, and everything is working perfectly. However, I encountered an issue when attempting to generate a PDF of this ...

The function is not being invoked, utilizing jQuery's .delegate method

Utilizing jquery delegate to call a function is effective. For example: $("body").delegate("div", "mouseover", function(){ alert("it works"); }); It also makes sense to reuse the same function in multiple places. Instead of duplicating the code, you can ...

When attempting to retrieve data from an API in Angular 8, I encountered difficulties in dynamically creating a formArray within a formArray

I am struggling to dynamically create form controls based on the data received, specifically for fields like task and template name. Your assistance is greatly appreciated. { "items": [ { "templatename": "Defult" ...

Rotating a camera in ThreeJS for a quick orbit

I am using an orbital camera that orbits around a globe with markers for users to interact with. When a user clicks on a marker, the camera moves to that specific point. To animate this movement, I am utilizing TweenMax as shown below: TweenMax.to(curre ...

Guide on enabling a new input field in React when a dropdown option is selected by a user

I'm attempting to show an additional input field when the user selects "Other" from the dropdown menu. I have implemented a state for the input field that toggles between true and false based on the selected value from the dropdown. However, I am enco ...

Having trouble with AES decryption on my nodeJS/ExpressJS server backend

Looking to decipher data post retrieval from mongoDb. The retrieved data comprises encrypted and unencrypted sections. app.get("/receive", async (req, res) => { try { const data = await UploadData.find(); const decryptedData = data. ...

Vue: The enigmatic world of ghost properties?

During my project work, I encountered the following code snippet: Main component - <ParameterModal>: <template> <modal-wrapper props="..."> <!-- ... other similar templates are present... --> <template v-else-if="moda ...

The loader image does not appear on mobile screens during an AJAX call, but it functions correctly on desktop screens

While I have successfully implemented a loader (.gif) using a div tag in an AJAX call for desktop screens, the same code is not functioning properly on mobile devices. Instead of displaying the loading animation, it simply shows a white screen. <div ...

Guide to setting up Mongodb with mongoose in the latest Next.js 13.3 update

I'm having trouble connecting MongoDB with Mongoose in Next.js 13.3 Version. I keep getting errors when trying to import the connectDb file or UserSchema file in api/getProducts/route.js file. Can someone please help me with step-by-step instructions ...

Consistently Encountering The 404 Error

Greetings! Below is the code snippet from my app.js: var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require(& ...

creating an unchanging array in the C++ programming language

Why does codeblocks keep telling me that I can't create an array? I'm just trying to write: const unsigned int ARRAY[10] = {0,1,2,3,4,5,6,7,8,9}; But every time I try, I get the following error message: Error: a brace-enclosed initializer is ...

The webpage is not displaying any results despite using .innerHTML with Ajax

I am currently developing a web application that displays query results using the Google Books API. While my code is functioning, I am encountering an issue where the .innerHTML method does not show any results on the HTML page. Below is the HTML code bein ...

Parse the JSON data response as needed in ReactJS

var mydata = [ { source: 11, Registernumber: ">RT-113, <RT-333", jul1: 1004 }, { source: 11, Registernumber: ">RT-113, <RT-333", jul2: 1234 }, // Rest of the data entries... ]; Can we transform the above JSON ...

Bootstrap 4 carousel is experiencing issues with the hasClass function

I'm working on a simple narrowcasting setup using a Bootstrap 4 carousel. Some of the slides in the carousel feature images, while others have Youtube videos embedded. My goal is to automatically play the Youtube video when its corresponding slide be ...

Displaying Angular table rows with missing values (Error: Cannot access property 'length' of undefined)

In the view, I have a table displaying nested data using ng-repeat. I want to show only rows with empty cells (<textarea>) when a link is clicked to apply a filter. The text of the link should change to 'Show all data' so that clicking it a ...

Extracting numbers using regular expressions can be tricky especially when dealing with mixed

Currently, I am attempting to create a javascript regex that can extract decimal numbers from a string containing a mix of characters. Here are some examples of the mixed strings: mixed string123,456,00indeed mixed string123,456.00indeed mixed string123,4 ...

The Bhoechie tab is malfunctioning following an AJAX request

I am currently using a Bhoechie tab that is built with JQuery. When the page initially loads, everything functions perfectly. However, once I make an ajax request to change the content of my tab menu, it no longer works correctly. How can I ensure that it ...

Tips for utilizing a function on an object

I was given a task that involves working with two arrays filled with random strings in Test.data. The goal is to create a single list containing elements alternating between the two arrays. For example: a: ['a', 'b', 'c'] ...

What is the best way to include the Mailchimp integration script in the `Head` of a Next.js project without causing any pre

Hello there Incorporating mailchimp integration into my nextjs site is proving to be a challenge. I've been attempting to add the following code snippet to next/Head within my custom _document <script id="mcjs">!function(c,h,i,m,p){m= ...

Is there a way to retrieve and store a JSON object from a URL using JavaScript and jQuery?

I have a PHP page that is returning a JSON object in the correct format, like this: [ { "name":"Users", "parent":"null", "children":[ { "name": "adsd", "parent": "Users", "children": [] } , { "name": "ca", "p ...