【问题标题】:Firebase TypeError: Cannot read property 'val' of undefinedFirebase TypeError:无法读取未定义的属性“val”
【发布时间】:2018-09-19 16:13:43
【问题描述】:

我已尝试使用 Firebase 云功能发送通知。我的项目结构

这是 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);
   });

以上代码配置错误,我在Node.js中部署时,LOG in Function显示:

“TypeError: 无法读取未定义的属性 'val'”。

实际上我正在尝试做什么: 我正在尝试从快照加载中提取信息到 index.js 中,这样当一个新的孩子被添加到实时数据库时,它应该触发一个带有标题和正文的通知负载。

在 Android 中,我使用子侦听器,用于在添加新记录时进行侦听

FirebaseDatabase.getInstance().getReference().child("messages")

 OnChildAdded(.....){
 if (dataSnapshot != null) {
                    MessageModel messageModel = dataSnapshot.getValue(MessageModel.class);
                    if (messageModel != null) {
                            // do whatever
                           }
                   }

但在 index.js 中,我无法解析它。 非常感谢根据我的数据库结构修复 index.js 的一些指导。 PS-我从来没有用JS写过代码 如果您需要更多上下文,我很乐意提供。

【问题讨论】:

    标签: javascript node.js firebase firebase-realtime-database google-cloud-functions


    【解决方案1】:

    改变这个:

    exports.pushNotification = functions.database.ref('/messages').onWrite( event => {
    
    const message = event.data.val();
    const user = event.data.val();
    });
    

    到这里:

    exports.pushNotification = functions.database.ref('/messages').onWrite(( change,context) => {
    
    const message = change.after.val();
    });
    

    请检查:

    https://firebase.google.com/docs/functions/beta-v1-diff#realtime-database

    云功能已更改,现在onWrite 有两个参数changecontext

    change 有两个属性 beforeafter,每个属性都是 DataSnapshot,方法如下:

    https://firebase.google.com/docs/reference/admin/node/admin.database.DataSnapshot

    【讨论】:

    • 谢谢彼得,我整天都在寻找这个解决方案!
    • @PeterHaddad 嘿,我想发送带有通知正文的用户名,这是它保存在我的数据库中的内容,就像这样 imgur.com/65Z25Rh ,我将它保存为像这样的变量 const userName = snapshot.after.val().username._55 但是日志告诉我 Cannot read property '_55' of undefined at exports.sendPushR.functions.database.ref.onWrite
    【解决方案2】:
    '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');
            });
        });
    });
    

    【讨论】:

      猜你喜欢
      • 2018-10-30
      • 2018-04-01
      • 2018-12-05
      • 2018-01-22
      • 2019-12-23
      • 2020-11-29
      • 2019-09-28
      • 2019-04-05
      • 2021-12-05
      相关资源
      最近更新 更多