Firebase TypeError: Cannot read property 'val' of undefined

I have tried Firebase cloud function for sending a notification.My project structure Database 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.


Solution 1:

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