【问题标题】:TypeError: Cannot Read Property child of undefinedTypeError:无法读取未定义的属性子项
【发布时间】:2018-09-26 15:26:56
【问题描述】:

我正在尝试制作一个 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 的结果是未定义的。问题是什么。我该如何解决?

我的实时数据库结构:

【问题讨论】:

  • 我还没有广泛使用云函数,但我认为这是节点的问题。先尝试打印change 的内容,看看你是否真的得到了正确的快照。
  • 如果您打算切换到 Firestore,我已经在我的一个教程中逐步说明了如何使用 Cloud Firestorenotifications 发送给特定用户和Node.js。你也可以看看我这个 post 的回答。

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


【解决方案1】:

改变这个:

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

onWriteonUpdate 都具有 change 参数,该参数具有前后字段。其中每一个都是DataSnapshot,与admin.database.DataSnapshot中提供的方法相同

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

【讨论】:

    猜你喜欢
    • 2019-02-19
    • 1970-01-01
    • 2021-09-08
    • 1970-01-01
    • 1970-01-01
    • 2020-11-29
    • 2019-01-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多