简体   繁体   中英

Firebase TypeError: Cannot read property 'val' of undefined

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.

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

'use strict'

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.sendNotification = functions.database.ref('/NOTIFICATIONS/{UserId}/{{notification_id}').onWrite((change, context) => 
{
    const UserId = context.params.UserId;
    const notification = context.params.notification;

    console.log('The user Id is : ', UserId);

    if(!change.after.exists())
    {
        return console.log('A Notification has been deleted from the database : ', notification_id);
    }

    if (!change.after.exists()) 
    {
        return console.log('A notification has been deleted from the database:', notification);
        return null;
    }

    const deviceToken = admin.database().ref(`/USER/${UserId}/device_token`).once('value');

    return deviceToken.then(result => 
    {
        const token_id = result.val();
        const payload = {
            notification : {
                title : "Friend Request",
                body : "You've received a new Friend Request",
                icon : "default"
            }
        };

        return admin.messaging().sendToDevice(token_id, payload).then(response => {

            console.log('This was the notification Feature');
        });
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM