Firebase - Targeting Specific Firestore Document Field with Cloud Functions

╄→гoц情女王★ 提交于 2020-06-10 09:16:37

问题


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": "john@gmail.com" } } }

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?


回答1:


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)



来源:https://stackoverflow.com/questions/46576393/firebase-targeting-specific-firestore-document-field-with-cloud-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!