0

My google cloud function is triggered when an update takes place on a document in my firestore database. The update would happen from a string being added/removed to an array in the database. How do I get the exact value added/removed to the database in the cloud function?

// Update event attendance
exports.updateEventAttendance = functions.firestore
    .document('users/{userId}')
    .onUpdate((change, context) => {
      const newValue = change.after.data();
      const oldValue = change.before.data();

      const newEvents = newValue.eventsAttended;
      const oldEvents = oldValue.eventsAttended;

      // We'll only update if the eventsAttended has changed.
      // This is crucial to prevent infinite loops.
      if (newEvents === oldEvents) return null;

      const newCount = newEvents.length;
      const oldCount = oldEvents.length;

      var db = admin.firestore()

      if (newCount > oldCount) {
        // Event added
        // Get event id
        // GET STRING THAT WAS ADDED TO THE DATABASE AND DO SOMETHING WITH IT

      } else if (oldCount > newCount) {
        // Event removed
        // Get event id
        // GET STRING THAT WAS REMOVED FROM DATABASE AND DO SOMETHING WITH IT
      }
      return null;
    });
Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
yambo
  • 1,388
  • 1
  • 15
  • 34
  • Your question boils down to just figuring out how to "diff" two arrays in JavaScript. There is nothing specific to Firestore in this task, as you've already determined which field has changed, and you already know the field is an array. The marked duplicate has some strategies for diffing two arrays in JS. – Doug Stevenson Jul 06 '19 at 00:48

1 Answers1

0

Cloud Functions tells you the document state before and after the write operation within its change.before and change.after parameters. It doesn't specify what specific fields were changed within the document, so you will have to determine that yourself by comparing the relevant fields in the before and after snapshots.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • In this case, the OP already knows which field changed (eventsAttended), and that it's an array. They just need to diff the arrays to find out what changed. – Doug Stevenson Jul 06 '19 at 00:50