Is there a way to have a firebase trigger which is triggered on updating multiple subcollections?

Viewed 23

I have been attempting to get the params and data of a multi subcollection level structure in firebase. I need to know all the documentIds at each level. I am using the onCreate trigger.

I have a structure like below:

utilities/gas/paymentTypes/card/dates/2020-01

and have been attempting to get the following parameters:

  • Utility Type e.g. gas
  • Payment Type e.g. card
  • Date e.g. 2020-01

The code I have been attempting to use is below:

export const addDistributionArea = functions.firestore.document("utilsTypesDistributionArea/{utilityType}/paymentTypes/{paymentType}/dates/{date}")
    .onCreate(async (snapshot: any, context: any) => {  
        console.log("params", context.params);
        console.log("id", snapshot.ref.id);
        console.log("data", snapshot.data());
        return null;

});

Currently I can retrieve utilityType and paymentType however {date} is always undefined.

Result:

>  params { utilityType: 'gas', paymentType: 'card', date: undefined }
>  id QDD_1
>  data {}

Could anyone please help me with finding a solution.

1 Answers

There is no Cloud Function that triggers across multiple writes like that.

Options I can think of:

  1. Write all data into a single document, and then fan the data out to the other collections as needed in your Cloud Function code.

  2. Trigger on each of the documents, and then detect whether all necessary documents exists inside your Cloud Function code. If not, ignore this trigger and wait for the other documents to appear.

Either of these can work, although personally I have a preference for the first as I like to see that combined document as the "transaction data" that the app posts atomically in that case.

Related