gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 22:08:21 26 4
gpt4 key购买 nike

我想通过 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com