简体   繁体   中英

How to use I-Value in for-loop

Hi I am playing around with javascript and firebase but running into an issue.

I want to sent the same email to every email listed in my datebase after the database entry hast been created:

在此处输入图片说明

If I use the code without the for-loop everything works fine:

to: snap.data().email,

I tried a few ways to use the i-value as an argument - one of them not working is in the code below:

to: snap.data().email.concat(i.toString()),
exports.sendEmail = functions.firestore
    .document('user/{userId}')
    .onCreate((snap, context) => {

      for(var i = 1; i <= snap.data().number; i++) {
        const mailOptions = {

            from: `***********`,
            to: snap.data().email.concat(i.toString()),
            subject: `From ${snap.data().name}`,
            html: `<h1>Me ${snap.data().name} </h1>
                                <p>
                                   <b>Hallo - </b>${snap.data().content}<br>
                                </p>`
      };
      return transporter.sendMail(mailOptions, (error, data) => {
          if (error) {
              console.log(error)
              return
          }
          console.log("sent")
      });
    };

    });

I would really appreciate if you could help me out :-)

if you want to get email1 , and email2 , ... properties, you can do as below

to: snap.data()['email'+i],

also to have better code, you can store snap.data() into a variable like

const data = snap.data();

and use it over and over like

to: data['email'+i]

Also you have return in your loop, it means after first one it will exit loop

Suggestion

You can store emails as an array, instead of one by one, then you can simply loop through and send emails, also then you don't need number, so you shape of data will be like

{
  content: string;
  name: string;
  emails: string[];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM