Home > Net >  Is it possible to access the subcollection of the collection on Cloud Firestore triggers via the cal
Is it possible to access the subcollection of the collection on Cloud Firestore triggers via the cal

Time:03-01

Let's say, I need to send an email to all the members of the group when the group is complete:

export const sendEmailToNewMember = functions.firestore.document('group/{groupId}').onCreate(async (snapshot,context) => {
}

The collection group has subcollection members. I check if the member's count has incremented and matches the total number of members who can join a group. If the final member has joined, I need to send all the members an email saying the group is complete.

The data structure looks like the one shown below:

collection group {
  membersCount: 9999,
  totalMembers: 100000,
  ....

  users subcollection
}

I tried accessing the collection through ref like so:

const usersRef = snap.ref.collection('users)

But, the result was undefined. For now, I access it using

await firestore().collection('group').doc(groupId).collection('users')

Is it possible to access the subcollection without awaiting it and from the snapshot itself?

CodePudding user response:

The document() takes path to a document and not a field. So if you want to trigger this function when any of the fields in group document is updated then set the path to .document('group/{groupId}').

Also snapshot in onCreate() will then contain data of that group's document only (the document that triggered the function). You'll have to explicitly read the sub-collection.

It seems you want to send email to new member that joins a group. You can instead trigger the function when a new user is added in user's sub-collection as shown below:

// Here user's UID would be ID of sub-document
export const sendEmailToNewMember = functions.firestore.document('group/{groupId}/users/{userId}').onCreate(async (snapshot,context) => {
  const { groupId, userId } = context.params;
}
  • Related