Reputation: 145
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:
Upvotes: 4
Views: 4023
Reputation: 80934
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
andonUpdate
have thechange
parameter which has before and after fields. Each of these is aDataSnapshot
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.
Upvotes: 4