Ad

Firebase Functions Only Sets First Value In Firebase Realtime Database

I'm trying to save some data to all subscribers of a group whenever a new event is added to their group. It seems to work but somehow firebase functions only saves the first value in my firebase realtime database.

Like you see in my code I'm doing this inside a forEach and also without a forEach. Depending on whether it's a single-event or a group-event. Outside the forEach it works perfectly and all the data is saved. However inside the forEach it only saves the 'title'. In the console.log() it shows me all the right values in the firebase functions console but still it won't appear in the realtime database.

 exports.saveNewEventToUsers = functions.database.ref('events/{groupId}/{eventId}').onCreate((snap, context) => {
  const root = snap.ref.root;
  // removed some consts for this example
  // if the groupId equals the creator it's a single-event ELSE a group-event
  if (groupId === data.creator) {
    singleEvent = true;
    return root.child(`userEvents/${groupId}/${eventId}`).set({ title, timestamp, singleEvent, creator, eventId, groupId });
  } else {
    return root.child(`groups/${groupId}/selected`).once('value', snapshot => {
      snapshot.forEach(user => {
        console.log(title, timestamp, singleEvent, creator, eventId, groupId);
        return root.child(`userEvents/${user.key}/${eventId}`).set({ title, timestamp, creator, eventId, groupId });
      }); // forEach
    });
  }
})

Here you see the single event and group event difference. It should always be like on the single eventThe logs also show up right

On the image you see that for single-events it works as expected but at group-events it only saves the title. Anybody any idea what causes the problem? What am I doing wrong? Thank you very much in advance for your help!

Ad

Answer

You're mixing callbacks and promises, so the function is terminating before you expect it to. Try something more like:

    return root.child(`groups/${groupId}/selected`).once('value').then(snapshot => {
      const sets = [];
      snapshot.forEach(user => {
        console.log(title, timestamp, singleEvent, creator, eventId, groupId);
        sets.push(root.child(`userEvents/${user.key}/${eventId}`).set({ title, timestamp, creator, eventId, groupId }));
      }); // forEach
      return Promise.all(sets);
    });
Ad
source: stackoverflow.com
Ad