jonnyc
jonnyc

Reputation: 217

Watch a collectionGroup with Firestore using Cloud Functions

I'm working on a Firestore DB that uses collectionGroups.

The collectionGroup in question is a collection of 'Fights'.

When a new fight is created I would like to use the onCreate method in a cloud function to watch for new 'Fight' entries and then add some meta data to them. Ideally It would look something like the pseudo code below

export const placeFightersInEvent = functions.firestore
  .collectionGroup('fights/{fightId}')
  .onCreate(async (fightSnapshot, context) => {
    // get metadata and add to the newly created 'fight'
  });

I'm using the most up to date versions of the firebase functions and admin sdk but I can't seem to find an available function to do this. Is it possible to watch collection groups in this way?

Upvotes: 5

Views: 1244

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317352

Currently this is not possible for fights subcollections at any depth. Please file a feature request with Firebase support if you need to do this.

However, if you are only ever working with a fights subcollections at a known depth, then this might work just as well anyway:

export const placeFightersInEvent = functions.firestore
  .document('{coll}/{doc1}/fights/{doc2}')
  .onCreate(async (fightSnapshot, context) => {
    // get metadata and add to the newly created 'fight'
  });

It should only trigger for new fights nested below documents in any top-level collection, so it is not a true collection group event handler. But you could just create new functions for each depth required.

Upvotes: 8

Related Questions