【问题标题】:Cloud Function - onWrite is not triggered when a new document is created云函数 - 创建新文档时不会触发 onWrite
【发布时间】:2021-01-19 09:52:42
【问题描述】:

我有一个“用户”集合,其中包含一个文档列表,每个文档都有一个用户对象和一个子集合“通知”。每当用户收到新通知时,都会在其子集合 Notifications 下创建一个新文档。

云端函数中的触发器未触发。

这是我的 Firestore 结构:

这是我的功能:

let functions = require('firebase-functions');
let admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.sendNotification = functions.firestore.collection('Users/{userID}/Notifications/{notificationId}')//
    .onWrite(async (change,context) => {

        // get receiver ID
        const receiverId = context.params.userID;

        // get notification object
        const notificationObject = change.after.val();
        // get sender ID
        const senderUid = notificationObject.senderId;

        console.log('sending notification to: ' + senderUid);

        if (senderUid === receiverId) {
            // this should never be called
            console.log('sender is the receiver.');
        }

        // receiver's token
        const getTokenPromise = await admin.firestore().collection('Users').doc(receiverId).once('value');
        const token = getTokenPromise.val().deviceToken;
        // sender user object
        const sender = await admin.firestore().collection('Users').doc(senderUid).once('value');

        const payload = {
            data: {
                senderName: sender.val().userName,
                senderPhoto: sender.val().userPhoto,
                object: JSON.stringify(notificationObject)
            }
        };

        try {
          const response = await admin.messaging().sendToDevice(token, payload);
          console.log("Successfully sent notification:", response);
        }
        catch (error) {
          console.log("Error sending notification:", error);
        }
    });

我做错了什么?

【问题讨论】:

  • 如何验证它没有被触发?来自 Cloud Functions 日志?我可以看到一个潜在的问题(未经测试):初始化时您不能再传入functions.config().firebase。见firebase.google.com/docs/functions/…
  • 感谢您的回复 Renaud,我更改了初始化,但仍未触发。我正在通过日志进行验证,并在 onMessageReceived 方法的客户端(android)上设置断点。

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


【解决方案1】:

你应该用

声明你的函数
exports.sendNotification = functions.firestore.document('Users/{userID}/Notifications/{notificationId}')//
    .onWrite(async (change,context) => {...});

而不是与

exports.sendNotification = functions.firestore.collection('Users/{userID}/Notifications/{notificationId}')//
    .onWrite(async (change,context) => {...});

事实上,Firestore 的 Cloud Functions 是在文档级别触发的。更多详情 herehere 在文档中。

【讨论】:

    猜你喜欢
    • 2019-09-09
    • 2019-05-05
    • 2021-06-02
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 2017-08-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多