firebasegoogle-cloud-platformgoogle-cloud-firestoregoogle-cloud-functions

do you need to create a separate collection/document for reading an aggregated document with firebase cloud function


I want to use cloud function to produce an aggregated document containing all the data i need for the first page of my app. The aggregated document will be updated each time a document is add/updated in a Firestore collection A. In order to do so, I have to create a separate collection B containing a single document(the aggregated doc from cloud function) which the app will fetch from when it start right? Hence, my cloud function will be updating the single document in Collection B? Am I correct in my understanding of how using cloud function to aggregate data works? Thank you very much


Solution

  • This is indeed a totally valid approach. Note that you may use a Transaction, in the Cloud Function, if there is a risk that source data is updated by several users in parallel.


    You don't give any detail on what is in collection A (identical docs or different docs?) and what is aggregated (numbers, headlines,...), but you should try to avoid reading all the docs from collection A each time the Cloud Function is triggered. This may generate some unnecessary extra cost. If the first page of your app aggregates some figures, you may use some counters.