1

Let's say my database looks like the following:

project
└── users
    ├── safuhf8sdf76fs
    │   ├── name: 'William'
    │   └── favoriteColor: 'blue'
    ├── sffuef5srf72fd
    │   ├── name: 'Emily'
    │   └── favoriteColor: 'yellow'
    └── rfdu4ffsgf42gi
        ├── name: 'Sam'
        └── favoriteColor: 'red'

I'm trying to create a Cloud Function that is triggered when the favoriteColor value of any user object is changed/added/removed.

The part I'm having trouble with is creating the reference to said key.

I know that I could listen to any and all changes to users with

exports.updatedFavoriteColor = functions.database.ref('/users').onWrite(event => { ... });

and then just check the data changed to see if it was favoriteColor.

While this would work, I'd much prefer a trigger that is specifically listening for the favoriteColor key of all user objects- something kind of like this: functions.database.ref('/users').child(?).child('favoriteColor')

My preferable function would be called when the favoriteColor of William or Emily is changed, but not when the name of Sam is changed, for example. Is this possible?

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
willbattel
  • 1,040
  • 1
  • 10
  • 37

1 Answers1

3

I think I figured it out with some more digging.

The Firebase docs suggest I can do the following:

exports.updatedFavoriteColor = functions.database.ref('/users/{pushId}/favoriteColor').onWrite(event => { ... });

This should get triggered by the change in favoriteColor for any user, where the particular user being updated is represented by the {pushId} in the reference. In the function itself, you can reference the user id with event.params.pushId

willbattel
  • 1,040
  • 1
  • 10
  • 37
  • 3
    *firebaser here* That's indeed the way to do it. Little note: the `event.data` in this case will only contain the previous and new value of `favoriteColor`. If you need the entire user node, you'll have to load it separately. Also see https://stackoverflow.com/questions/45491967/firebase-get-parrent-of-parent-data-before-delete/45492805#45492805 – Frank van Puffelen Oct 02 '17 at 02:51