无法读取未定义的属性"user_id" [英] Cannot read property 'user_id' of undefined

查看:211
本文介绍了无法读取未定义的属性"user_id"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过Firebase云功能将设备发送到设备推送通知.我正在编写node.js脚本

I want to send device to device push notification through firebase cloud functions. I am writing node.js script

exports.sendNotification = functions.database.ref('/messages/{user_id}/{rec_user_id}').onWrite((event) => {

const sender_user_id = event.params.user_id;
const receiver_user_id = event.params.rec_user_id;

console.log('We have a notification from : '+ sender_user_id+  " | Receiced by " + receiver_user_id);

return;

});

在Firebase云上部署功能后,出现错误

After deploying function on firebase cloud i got an error

TypeError: Cannot read property 'user_id' of undefined

完整的错误日志是:

TypeError: Cannot read property 'user_id' of undefined
at exports.sendNotification.functions.database.ref.onWrite.event (/user_code/index.js:28:40)
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:700:26
at process._tickDomainCallback (internal/process/next_tick.js:135:7)

我从此处得到了答案

I got an answer from here

它工作正常,但是当我使用

It was working fine, but when i used

if(!event.data.val()){

return console.log('A Notification has been deleted from the database : ', sender_user_id);

}

Firebase日志再次开始向我显示一条错误消息

Firebase log again start to give me an error message saying

Cannot read property 'val' of undefined

如何摆脱这些错误? 预先感谢

How to get rid of these errors ? Thanks in advance

推荐答案

关于val(),您需要执行以下操作:

Regarding val() you need to do the following:

exports.sendNotification = functions.database.ref('/messages/{user_id}/{rec_user_id}').onWrite((change,context) => {

const afterData=change.after.val();
});

由于您使用的是onWrite(),因此数据参数应该为change,它具有beforeafter属性,它们每个都是具有以下方法的DataSnapshot:

Since you are using onWrite() then the data parameter should be change, which has the before and after properties, each of these is a DataSnapshot that has the following methods:

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

也供参考:

https://firebase.google.com/docs/reference/functions /functions.Change

这篇关于无法读取未定义的属性"user_id"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆