Home > Blockchain >  Firebase functions: onChange for subcollections
Firebase functions: onChange for subcollections

Time:08-03

Im making a type of chat app. The structure is something like this: there is a special type of user, a stingray, represented by a document. Each stingray can hold a collection of messages,'messages', which holds different chat data models with unique id's. It looks like this:

enter image description here

Im trying to implement a cloud function that listens to the stingray collection, and when a message document is updated, send a push notification to the relevant user. Is this possible? Im confused on how to implement it, because there can be multiple stingrays, each with their own 'messages' collection.

Thank you!

CodePudding user response:

You can write a Cloud Function that triggers on all stingrays subcollections with:

exports.myFunction = functions.firestore
  .document('/stingrays/{docId}')
  .onWrite((change, context) => { /* ... */ });

Also see the documentation on Firestore triggers for Cloud Functions.

If the stingrays are subcollections of (for example) documents in a collection called toplevel, you can trigger on all of them with:

exports.myFunction = functions.firestore
  .document('/toplevel/{toplevelId}/stingrays/{docId}')
  .onWrite((change, context) => { /* ... */ });

In both cases, you can get the value of the parameters in the path with context.params.docId and (in the latter case) context.params.toplevelId.

  • Related