在子集合更新时触发云功能

时间:2020-12-22 10:54:44

标签: javascript node.js firebase google-cloud-firestore google-cloud-functions

我知道这个问题已经有人问过了,但没有帮助。 我有一个包含一个文档“成员”和一个子集合“消息”的“聊天”集合,我想在子集合中添加新消息时触发云功能。

这是我尝试过的,但它仅在“成员”更新时触发,并且没有关于子集合的任何信息:

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);});

我的 Firestore 收藏: enter image description here

我的问题是如何在子集合更新时触发云功能?

1 个答案:

答案 0 :(得分:6)

当您修改 chats 集合的文档时(例如,如果您修改 members 文档的 G162R... 字段),您的 Cloud Function 不会被触发。

当您修改(而不是创建)messages 集合中文档的 chats 子集合中的文档时,将触发您的云函数。例如,如果您更改消息文档 textvVwQXt.... 字段的值。


所以,回答你的问题

<块引用>

我的问题是如何在子集合上触发云函数 更新

如果“子集合更新”是指子集合中现有文档的更新,则您的云函数是正确的。

如果“子集合更新”是指在子集合中创建文档(可以是“子集合更新”的一种解释) ),您应该将触发器类型从 onUpdate() 更改为 onCreate()

从您问题中的以下句子,即“我想在子集合中添加新消息时触发云功能”,似乎您想要第二个情况,因此您应该按如下方式调整您的 Cloud Function:

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

})

doc 中有更多详细信息。