首页 > 解决方案 > 云函数 - 创建新文档时不会触发 onWrite

问题描述

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

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

这是我的 Firestore 结构:

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

我做错了什么?

标签: javascriptnode.jsfirebasegoogle-cloud-firestoregoogle-cloud-functions

解决方案


你应该声明你的函数

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 in the doc。


推荐阅读