Cannot read property 'user_id' of undefine

2019-07-31 17:42发布

问题:

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;

});

After deploying function on firebase cloud i got an error

TypeError: Cannot read property 'user_id' of undefined

Full error log is :

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 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

回答1:

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();
});

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

Also for reference:

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