TypeError:无法读取未定义的属性“receiver_id”

Posted

技术标签:

【中文标题】TypeError:无法读取未定义的属性“receiver_id”【英文标题】:TypeError: Cannot read property 'receiver_id' of undefined 【发布时间】:2018-12-14 12:48:31 【问题描述】:

此功能是当有人向他发送请求时向用户发出通知 我正在创建一个用于学习目的的消息传递应用程序,但无法解决该问题。 firebase 控制台不断给出错误:firebase 函数

TypeError: Cannot read property 'receiver_id' of undefined
   at exports.sendNotification.functions.database.ref.onWrite.event 
(/user_code/index.js:9:36)
at Object.<anonymous> (/user_code/node_modules/firebase-functions/lib/cloud- 
   functions.js:112:27)
    at next (native)
at /user_code/node_modules/firebase-functions/lib/cloud-functions.js:28:71
at __awaiter (/user_code/node_modules/firebase-functions/lib/cloud- 
   functions.js:24:12)
at cloudFunction (/user_code/node_modules/firebase-functions/lib/cloud- 
   functions.js:82:36)
at /var/tmp/worker/worker.js:728:24
    at process._tickDomainCallback (internal/process/next_tick.js:135:7)

-----我的代码是-----

'use strict'

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification = 
functions.database.ref('/Notifications/receiver_id/notification_id')
        .onWrite(event => 
       
           const receiver_id = event.params.receiver_id;
        console.log('We ahve a notification to send to : ', receiver_id);
        if(!event.data.val())
        return console.log('Notification has been deleted', notification_id);
    const DeviceToken = admin.database().ref(`/users/$receiver_id/device_token`).once(value);
    return DeviceToken.then(result =>
    
        const token_id=result.val();
        const payload=
            notification:
            
                title : "Friend Request",
                body : "you have recived a new friend request",
                icon : "default"
            
        ;
        return admin.messaging().sendToDevice(token_id,payload)
            .then(response =>
            
                return console.log('This is notification');
            );
        );
    );

【问题讨论】:

onWrite 中的event 里面有什么?错误消息告诉您paramsevent.params.received_id 中未定义 【参考方案1】:

paramsonWrite 回调函数的2nd parameter 提供。

.onWrite((snapshot, context) => 
  const receiver_id = context.params.receiver_id;
);

【讨论】:

现在它返回另一个错误TypeError: Cannot read property 'val' of undefined at exports.sendNotification.functions.database.ref.onWrite

以上是关于TypeError:无法读取未定义的属性“receiver_id”的主要内容,如果未能解决你的问题,请参考以下文章

TypeError:无法读取未定义的属性“findAll”(expressjs)

TypeError:无法读取未定义的属性(读取“问题”)

TypeError:无法读取未定义的属性“babel”

TypeError:无法读取未定义的属性(读取“匹配”):

TypeError:无法读取未定义的属性“存在”

TypeError:无法在 gitlab 中读取未定义的属性(读取“读取”)