javascript - 类型错误 : Cannot Read Property child of undefined

标签 javascript firebase firebase-realtime-database firebase-cloud-messaging google-cloud-functions

我正在尝试创建一个 node.js firebase 函数,以便在我的实时数据库中每次在“通知”父节点内添加或更新节点时向用户发送通知。

这是我的 index.js-

let functions = require('firebase-functions');

let admin = require('firebase-admin');

admin.initializeApp();

exports.sendNotification = functions.database.ref('/Notifications/{postId}').onWrite((change, context) => {

//get the userId of the person receiving the notification because we need to get their token
 const receiverId = change.after.data.child('receiver_token').val();
 console.log("receiverId: ", receiverId);



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



  const token = receiver_token;

  console.log("Construction the notification message.");
  const payload = {
    data: {
      data_type: "direct_message",
      title: "Open Up",
      message: message,

    }
  };

  return admin.messaging().sendToDevice(token, payload);
});

但每次都会出现错误,因为它说 change.after.data 的结果是未定义的。问题是什么。我该如何解决?

我的实时数据库结构:

enter image description here

最佳答案

改变这个:

const receiverId = change.after.data.child('receiver_token').val();
console.log("receiverId: ", receiverId);
//get the message
const message = change.after.data.child('content').val();
console.log("message: ", message); 

进入这个:

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

Both onWrite and onUpdate have the change parameter which has before and after fields. Each of these is a DataSnapshot with the same methods available in admin.database.DataSnapshot

admin.database.DataSnapshot 不包含名为 data 的字段,这就是您收到未定义错误的原因。

关于javascript - 类型错误 : Cannot Read Property child of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52521318/

相关文章:

javascript - 尝试连接数字和字符串时出现 NaN Javascript 和 Jquery 错误

android - Android 上的 Firebase - 我想在 Android 客户端上禁用 firebase 通知

javascript - 如何让 Firestore 交易返回 promise ?

ios - 如何使用 Firebase 确保我的代码在 Swift 中按顺序运行?

javascript - 如何将 Firebase 中的节点(对象)复制到另一个节点?

JavaScript document.createElement 不显示

javascript - 返回值时 `each` 与 `for-loop` 有何不同?

javascript - 切换可见性 - 显示/隐藏 - 切换时保持显示

java - 模拟 firebase android 应用程序

java - 如何对多个 child 执行查询?