TypeError:无法读取未定义的属性子级

时间:2018-09-26 15:26:56

标签: android 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

1 个答案:

答案 0 :(得分:3)

更改此:

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的字段,这就是为什么您会得到未定义的错误的原因。