Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase - Targeting Specific Firestore Document Field with Cloud Functions

When using Cloud Functions with the Firebase Realtime Database you are able to target a specific field with a cloud function. For example, given this JSON structure, I could target when user1's email field changed with a ('/user/{userId}/email').onUpdate cloud function.

{ "user": { "user1": { "name": "John Doe", "phone": "555-5555", "email": "[email protected]" } } }

Now with Firestore it seems that I can't target a specific field and can only target documents. If this is the case a Firestore cloud function to target the email field would have to look like this, ('/user/{userId}').onUpdate, and fire every time any document in the user collection changed. This would result in a lot of wasted cloud functions firing. Is this how Firestore works and is there an elegant work around to it?

like image 742
CWiley Avatar asked Oct 05 '17 01:10

CWiley


1 Answers

You are correct, due to the different data models Cloud Firestore only allows you to trigger Cloud Functions on document level events rather than field level.

One method is to store email in a separate document (e.g. in a subcollection called Email), so updating email is tye only change that will fire. This does require you reading an extra document each time you need the email though.

Another similar method is to still have it in the same document, but also write it into the subcollection as a second write to trigger the function. Use email as the doc I'd and have a timestamp field in the document to make it easy to clean up the old document ( select oldest email doc to delete, maybe even in the function)

like image 54
Dan McGrath Avatar answered Oct 31 '22 18:10

Dan McGrath