javascript - 无法读取未定义的属性 'user_id'

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

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

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 Cloud 上部署函数后出现错误

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)

我得到了 here 的答复

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

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

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

}

Firebase 日志再次开始给我一条错误消息

Cannot read property 'val' of undefined

如何消除这些错误? 提前致谢

最佳答案

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

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

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

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

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

另供引用:

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

关于javascript - 无法读取未定义的属性 'user_id',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49708163/

相关文章:

javascript - 在公司内部网上使用 GSuite 和谷歌身份的 api

javascript - JavaScript 的工作原理 : inside the V8 engine?

javascript - 用于 createUserWithEmailAndPassword 的 Firebase 和验证码

android - 如果 onPause() 或 onStop() 使用 Firebase 数据库中的嵌套回调中断函数,会发生什么

firebase - Pushsharp 4.0 与 Firebase

Javascript:重新加载 DIV 后按钮被禁用

javascript - 获取 span 元素的名称属性

node.js - Mocha,如何忽略 node_modules 文件夹

javascript - 如何从 Nodejs 后端的 JSON 填充 React 数组

javascript - 启用 CSP 策略导致前端的 javascript 不发送 cookie 和引用 header ?