Firebase TypeError: Cannot read property 'val' of undefined
Change this:
exports.pushNotification = functions.database.ref('/messages').onWrite( event => {
const message = event.data.val();
const user = event.data.val();
});
to this:
exports.pushNotification = functions.database.ref('/messages').onWrite(( change,context) => {
const message = change.after.val();
});
Please check this:
https://firebase.google.com/docs/functions/beta-v1-diff#realtime-database
The cloud functions were changed and now onWrite
has two parameters change
and context
The change
has two properties before
and after
and each of these is a DataSnapshot
with the methods listed here:
https://firebase.google.com/docs/reference/admin/node/admin.database.DataSnapshot
Comments
-
notTdar almost 2 years
I have tried Firebase cloud function for sending a notification.My project structure
and this is the index.js,
const functions = require('firebase-functions'); const admin = require('firebase-admin'); admin.initializeApp(); exports.pushNotification = functions.database.ref('/messages').onWrite( event => { console.log('Push notification event triggered'); const message = event.data.val(); const user = event.data.val(); console.log(message); console.log(user); const topic = "myTopic"; const payload = { "data": { "title": "New Message from " + user, "detail":message, } }; return admin.messaging().sendToTopic(topic, payload); });
The above code is misconfigured, when I deploy in Node.js, LOG in Function shows:
"TypeError: Cannot read property 'val' of undefined".
What Actually I am trying to do : I am trying to extract info from snapshot load into that index.js so that when a new child gets added to Real-time database, it should trigger a notification payload with a title and body.
In Android, I use a child listener, for listening when a new record is added
FirebaseDatabase.getInstance().getReference().child("messages") OnChildAdded(.....){ if (dataSnapshot != null) { MessageModel messageModel = dataSnapshot.getValue(MessageModel.class); if (messageModel != null) { // do whatever } }
But in index.js, I could not able to parse that. A bit guidance how to fixate index.js according to my database structure would be immensely appreciated. PS- I have never done coding in JS If you want more context, I'd be happy to provide it.
-
Kerrin631 about 6 yearsThank you Peter, I have been searching for this solution all day!
-
DevAS almost 5 years@PeterHaddad hey, I want to send the username with the body of notify and here is what it save in my DB like this imgur.com/65Z25Rh , and i save it a variable like this
const userName = snapshot.after.val().username._55
but the logs tell me Cannot read property '_55' of undefined at exports.sendPushR.functions.database.ref.onWrite