3
votes

I know that this question is already asked but it didn't help. I have a "chats" collection with one document "members" and a sub-collection "messages" and I would like to trigger a cloud function when a new message is added in the sub-collection.

This is what I tried but it is only triggered when "members" is updated, and does not have any information on the sub-collection:

exports.chatsCollectionTriggers = functions.firestore.document('/chats/{chatId}/messages/{messageId}').onUpdate(async (change, context) => {

let chatBefore = change.before.data();
let chatAfter = change.after.data();

console.log(JSON.stringify(chatBefore, null, 2));
console.log(JSON.stringify(chatAfter, null, 2));

console.log(context.params.chatId);
console.log(context.params.messageId);});

My firestore collection : enter image description here

My question is how can I trigger a cloud function on a sub-collection update ?

1

1 Answers

11
votes

Your Cloud Function will not be triggered when you modify a document of the chats collection (e.g. if you modify the members field of the G162R... document).

Your Cloud Function will be triggered when you modify (not when you create) a document in the messages subcollection of a document in the chats collection. For example, if you change the value of the text field of the message document vVwQXt.....


So, to answer to your question

My question is how can I trigger a cloud function on a sub-collection update

If by "sub-collection update" you mean the update of an existing document in a subcollection, your Cloud Function is correct.

If by "sub-collection update" you mean the creation of a new document in a subcollection (which can be one interpretation of "a sub-collection update"), you should change your trigger type from onUpdate() to onCreate().

From the following sentence in your question, i.e. "I would like to trigger a cloud function when a new message is added in the sub-collection", it seems you want to go for the second case, so you should adapt you Cloud Function as follows:

exports.chatsCollectionTriggers = functions.firestore.document('/chats/{chatId}/messages/{messageId}').onCreate(async (snap, context) => {

    const newValue = snap.data();

    console.log(newValue);

    console.log(context.params.chatId);
    console.log(context.params.messageId);

    return null;   // Important, see https://firebase.google.com/docs/functions/terminate-functions

})

More details in the doc.