Firebase 实时数据库获取通配符数据

Firebase realtime database get wildcard data

我正在尝试在用户的邮件收到新回复时向他们发送通知。但是,在 firebase 云函数日志中,它返回错误并且不发送通知。这是错误:

TypeError: Cannot read properties of undefined (reading 'uid') 

这是我的函数:

const functions = require("firebase-functions");
const admin = require("firebase-admin");

exports
    .sendNewTripNotification = functions
        .database
        .ref("messagepool/{uid}/responses/")
        .onWrite((event)=>{
          const messageid = event.params.uid;

          // console.log('User to send notification', uuid);

          const ref = admin.database().ref(`messagepool/${messageid}/author`);
          return ref.once("value", function(snapshot) {
            const ref2 = admin.database().ref(`users/${snapshot.val()}/token`);
            return ref2.once("value", function(snapshot2) {
              const payload = {
                notification: {
                  title: " New Reply",
                  body: "You have received a new reply to your message!",
                },
              };

              admin.messaging().sendToDevice(snapshot2.val(), payload);
            }, function(errorObject) {
              console.log("The read failed: " + errorObject.code);
            });
          }, function(errorObject) {
            console.log("The read failed: " + errorObject.code);
          });
        });

我是不是读错了通配符 uid?为什么会这样?

onWrite() takes 2 parameters - change that is a DataSnapshot and context 中的函数,其中包含您要查找的 params。尝试重构代码,如下所示:

exports
  .sendNewTripNotification = functions
  .database
  .ref("messagepool/{uid}/responses/")
  .onWrite((change, context) => {

    const { uid } = context.params;
    console.log('UID:', uid);

  })