praveen agrawal
praveen agrawal

Reputation: 21

Cloud function trigger for multiple collections which start with a same text

I know one can add a trigger to all the documents of a particular collection like

functions.firestore.document('Subscriber/{userID}').onCreate((snap, context)

But I have multiple collections like Subscriber1, Subscriber2, Subscriber3 and so on. Is there a way to write a trigger when any change happens to any collection which starts with Subscriber. Something like

functions.firestore.document('Subscriber**/{userID}').onCreate((snap, context)

Upvotes: 2

Views: 1422

Answers (2)

Wes1324
Wes1324

Reputation: 1123

I settled on exporting various cloud functions in my index.ts file, all of which listen for events in different collections but then delegate to the same function.

export const onSubscriberOneDocumentCreated = functions.firestore.document('/Subscriber1/{id}').onCreate(onSubscriberDocCreated);

export const onSubscriberTwoDocumentCreated = functions.firestore.document('/Subscriber2/{id}').onCreate(onSubscriberDocCreated);

export const onSubscriberThreeDocumentCreated = functions.firestore.document('/Subscriber3/{id}').onCreate(onSubscriberDocCreated);

async function onSubscriberDocCreated(snapshot: functions.firestore.QueryDocumentSnapshot) {
    // Add logic you want to perform when a document is created in the Subscriber1, Subscriber2 or Subscriber3 collection here
}

Upvotes: 3

Doug Stevenson
Doug Stevenson

Reputation: 317467

No, there are no regular expressions or substring matches in Cloud Functions triggers. You need to either specify the full name of the collection to trigger on, or wildcard the entire collection name. You can always check the name of the collection in the trigger code to see if it matches a pattern you expect, then return early if it's not.

Top-level collection names with highly variable values are usually a symptom of database design that's working against the way Firestore was intended to be used.

Upvotes: 3

Related Questions