设备到设备推送通知Firebase-onWrite问题

时间:2019-04-24 04:27:26

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

我有一个Android应用程序,希望人们(经过身份验证的用户)从消息框相互发送推送通知。我正在使用具有Firebase云功能的node.js,并且在日志中收到此错误

  

TypeError:无法读取未定义的属性'userId'       在exports.sendNotification.functions.database.ref.onWrite.event(/user_code/index.js:10:33)   ...

消息已成功写入实时数据库,但未将通知传递给接收者(用户)。

我阅读了很多文档和相同/相似的问题,所以我知道有很多与此相关的主题,但是我无法解决问题。我使用index.js作为源代码,但根据阅读的文档更改了某些部分,例如onWrite部分。

以下代码中的错误表示const receiverId = context.params.userId; 有关参数的某些信息出错了。这是代码的一小部分(根据我的更改):

let functions = require('firebase-functions');
let admin = require('firebase-admin');
admin.initializeApp();

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

//get the userId of the person receiving the notification because we need to get their token
const receiverId = context.params.userId;
console.log("receiverId: ", receiverId);

//get the user id of the person who sent the message
const senderId = change.child('user_id').val();
console.log("senderId: ", senderId);

//get the message
const message = change.child('message').val();
console.log("message: ", message);

//get the message id. We'll be sending this in the payload
const messageId = context.params.messageId;
console.log("messageId: ", messageId);

...

1 个答案:

答案 0 :(得分:0)

获取最新版本的节点 并参见:https://firebase.google.com/docs/functions/database-events#handle_event_data,了解onWrite(event ...)和onCreate(.....)的用法 那会帮助你