简体   繁体   中英

Cloud Functions for Firebase: How do I trigger a database function for a specific child key of all children

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?

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

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