我正在尝试创建一个 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 的结果是未定义的。问题是什么。我该如何解决?
我的实时数据库结构:
最佳答案
改变这个:
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
andonUpdate
have thechange
parameter which has before and after fields. Each of these is aDataSnapshot
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/