我正在尝试使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的结果是不确定的。问题是什么。我该如何解决?
我的实时数据库结构:
答案 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);
中可用的相同方法
onWrite
和onUpdate
都具有change
参数,该参数具有在字段之前和之后。每个都是DataSnapshot
,具有admin.database.DataSnapshot
admin.database.DataSnapshot
不包含名为data
的字段,这就是为什么您会得到未定义的错误的原因。