Firebase realtime database get wildcard data

Viewed 38

I'm trying to send a notification to users whenever their message receives a new reply. However, in the firebase cloud functions logs it is returning errors and not sending a notification. Here is the error:

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

Here is my function:

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

Am I reading the wildcard uid incorrectly? Why is this happening?

1 Answers

The function in onWrite() takes 2 parameters - change that is a DataSnapshot and context which contains the params you are looking for. Try refactoring the code as shown below:

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

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

  })
Related