4

I am trying to make a node.js firebase function to send a notification to the user each time a node is added or updated inside the 'Notifications' parent node in my realtime database.

Here is my index.js-

let functions = require('firebase-functions');

let admin = require('firebase-admin');

admin.initializeApp();

exports.sendNotification = functions.database.ref('/Notifications/{postId}').onWrite((change, context) => {

//get the userId of the person receiving the notification because we need to get their token
 const receiverId = change.after.data.child('receiver_token').val();
 console.log("receiverId: ", receiverId);



 //get the message
 const message = change.after.data.child('content').val();
 console.log("message: ", message);



  const token = receiver_token;

  console.log("Construction the notification message.");
  const payload = {
    data: {
      data_type: "direct_message",
      title: "Open Up",
      message: message,

    }
  };

  return admin.messaging().sendToDevice(token, payload);
});

But everytime the error comes as it says the result of change.after.data is undefined. What is the problem. How do I fix it?

My Realtime Database structure:

enter image description here

Peter Haddad
  • 78,874
  • 25
  • 140
  • 134
Bitten Tech
  • 125
  • 1
  • 10
  • 1
    I haven't used Cloud Functions extensively yet, but I think this is an issue with nodes. Try printing the content of `change` first and see if you're actually getting the right snapshot. – AL. Sep 26 '18 at 15:31
  • If you intend to switch to Firestore, I have exaplained in one of my tutorials step by step, how you can send **[notifications](https://www.youtube.com/watch?v=6RzB4HXzQyA&t=3s&list=PLn2n4GESV0AmXOWOam729bC47v0d0Ohee&index=17)** to specific users using `Cloud Firestore` and `Node.js`. You can also take a look at my answer from this **[post](https://stackoverflow.com/questions/48298993/push-notifications-on-content-change/48299840)**. – Alex Mamo Sep 26 '18 at 15:43

1 Answers1

4

Change this:

const receiverId = change.after.data.child('receiver_token').val();
console.log("receiverId: ", receiverId);
//get the message
const message = change.after.data.child('content').val();
console.log("message: ", message); 

into this:

const receiverId = change.after.child('receiver_token').val();
console.log("receiverId: ", receiverId);
//get the message
const message = change.after.child('content').val();
console.log("message: ", message);

Both onWrite and onUpdate have the change parameter which has before and after fields. Each of these is a DataSnapshot with the same methods available in admin.database.DataSnapshot

admin.database.DataSnapshot does not contain a field called data that is why you get undefined error.

Community
  • 1
  • 1
Peter Haddad
  • 78,874
  • 25
  • 140
  • 134