我想通过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云上部署功能后出现错误
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
如何摆脱这些错误? 提前致谢
答案 0 :(得分:1)
关于val()
,您需要执行以下操作:
exports.sendNotification = functions.database.ref('/messages/{user_id}/{rec_user_id}').onWrite((change,context) => {
const afterData=change.after.val();
});
由于您使用的是onWrite()
,因此数据参数应为change
,其中包含before
和after
属性,每个属性都为DataSnapshot
有以下方法:
https://firebase.google.com/docs/reference/admin/node/admin.database.DataSnapshot
另作参考:
https://firebase.google.com/docs/reference/functions/functions.Change