0

A firebase event which listents for changes.

exports.sendTestEmail = functions.database.ref('/email/{pushID}')
  .onWrite(event => {

    // Only edit data when it is first created.
    if (event.data.previous.exists()) {
      return;
    }
    // Exit when the data is deleted.
    if (!event.data.exists()) {
      return;
    }

    return sendTestEmail(event);
  });

function sendTestEmail(email, event) {

    const users = event.data.val();
    console.log(users);

  });
}

this is the result for console.log(users):

{ '-Km8VHEPHExBtpIN_7q0': 
   { admin: 'false',
     birthday: '76',
     description: 'desc',
     email: 'user@gmail.com',
     first_name: 'fname',
     last_name: 'lname',
     level: 5,
     occupation: 'dev',
     occupationLevel: 'dev5',
     phone: '+8766',
     verified: false },
  '-KmSjAaxdCUvrPEQ8InI': 
   { admin: 'false',
     birthday: '1990',
     description: 'desc',
     email: 'email2@gmail.com',
     first_name: 'fname',
     last_name: 'lanam3',
     level: 4,
     occupation: 'dev',
     occupationLevel: 'dev4',
     phone: '+23434',
     verified: false } }

I can't seem to loop and get the emails which are needed for sending emails to users who own the email addresses.

AL.
  • 36,815
  • 10
  • 142
  • 281
Ciprian
  • 3,066
  • 9
  • 62
  • 98
  • Try looking at this question here. https://stackoverflow.com/questions/921789/how-to-loop-through-plain-javascript-object-with-objects-as-members You have a plain old json object, why not just loop through that. – Thomas Valadez Jun 12 '17 at 21:52

1 Answers1

0

Maybe consider something like this.

function sendTestEmail(event) {
    emails = [];  // create empty email array
    const users = event.data.val(); // get users, as you currently were.
    for (var key in users) { // loop through users to retrieve key.
        var email = users[key].email; // get email using key
        emails.push(email); // push to emails array
    }
    return emails;
}
Thomas Valadez
  • 1,697
  • 2
  • 22
  • 27