4
votes

We a schema-less model where I would like to trigger a cloud function when a document is added to a defects collection. The thing is that any defect can contain a group of new defects collection (recursive).

How can I setup a cloud function that triggers on any of the following documents is updates / created:

problem/defects/{document}

problem/defects/{document}/defects/{document}

problem/defects/{document}/defects/{document}/defects/{document}

problem/defects/{document}/defects/{document}/defects/{document}/defects/{document}

and so on...

2
should it not be possible with a collectionGroup?p2hari
Can you trigger a cloud function with a collectionGroup?ejazz
sorry, yes it does not support. I thought you could just have a trigger with problem/defects/{wildcard}/ and the it would trigger for all writes within. The documentation says it is not possible :(p2hari
I sadly came to the same conclusion before posting this question :)ejazz

2 Answers

2
votes

Cloud Functions triggers do not allow wildcards that span more than one name of collection or document ID. If you need a function to fire on any number of paths, you will need to define them each separately, but each function can share a common implementation, like this:

functions.firestore.document("coll1/doc").onCreate(snapshot => {
    return common(snapshot)
})

functions.firestore.document("coll2/doc").onCreate(snapshot => {
    return common(snapshot)
})

function common(snapshot) {
    // figure out what to do with the snapshot here
}
2
votes

With firestore functions, you can use wildcard paths to trigger for every possible path. However, you will need to specify a trigger for each level of document (i.e. - depth=1, depth=2,depth=3, etc...). Here is mine that I wrote to handle up to 4 levels deep:

const rootPath = '{collectionId}/{documentId}';
const child1Path = '{child1CollectionId}/{child1DocumentId}';
const child2Path = '{child2CollectionId}/{child2DocumentId}';
const child3Path = '{child3CollectionId}/{child3DocumentId}';

export const onCreateAuditRoot = functions.firestore
  .document(`${rootPath}`)
  .onCreate(async (snapshot, context) => {
    return await updateCreatedAt(snapshot);
  });

export const onCreateAuditChild1 = functions.firestore
  .document(`${rootPath}/${child1Path}`)
  .onCreate(async (snapshot, context) => {
    return await updateCreatedAt(snapshot);
  });

export const onCreateAuditChild2 = functions.firestore
  .document(`${rootPath}/${child1Path}/${child2Path}`)
  .onCreate(async (snapshot, context) => {
    return await updateCreatedAt(snapshot);
  });

export const onCreateAuditChild3 = functions.firestore
  .document(`${rootPath}/${child1Path}/${child2Path}/${child3Path}`)
  .onCreate(async (snapshot, context) => {
    return await updateCreatedAt(snapshot);
  });