Search code examples
javascriptfirebasegoogle-cloud-platformgoogle-cloud-firestoregoogle-cloud-functions

Cloud Firestore is not triggering onWrite in wildcard


I am trying write an aggragation function to update a few details on a value change of a nested object of a doc in wildcard.

exports.createAccessDetails = functions.firestore.document('classrooms/{classId}/access/{accessType}').onWrite((snap, context) => {
  // const data = snap.data();
  const { classId, accessType } = context.params;
  console.log(snap);
  console.log(classId, accessType);
  return null;
});

Then updating the object like on a button click

function setAccess() {
  const date = Date.now();
  Firebase.firestore.collection('classrooms')
    .doc('1570776211111').update({
      [`access.writeAccess.${date}`]: true
    });
}

What am I doing wrong? Why the function didnt trigger?


Solution

  • From your comment above, it appears that you want to write (update) a document of the classrooms collection. More precisely, update the access field which is of type Map (see doc for Firestore types).

    So your Cloud Function shall simply be triggered when you update this document and to get the value of the access map you will call snap.data().access.

    exports.createAccessDetails = functions.firestore.document('classrooms/{classId}').onWrite((snap, context) => {
      const data = snap.data();
    
      const accessMap = snap.data().access;
      const writeAccessMap = accessMap.writeAccess
    
      //........
    
      return null;
    });
    

    Update following your comment below:

    I don't have a full view of your exact business requirements (in particular I see that you mention writeAccess and readAccess) but you could maybe have the following approach:

    For each classroom doc you create two sub-collections: writeAccess and readAccess. Each time you want to save an access you write a new document in one of these collections.

    You can then query the sub-collections to find the docs where a given id has read or write access. Then from the QueryDocumentSnapshot returned by these queries you can find the parent document (through the ref property).

    However, this means that you will have an extra read to get the classroom details from the results of the queries to the writeAccess and readAccess collections.