【发布时间】: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 Firestore将 notifications 发送给特定用户和Node.js。你也可以看看我这个 post 的回答。
标签: javascript firebase firebase-realtime-database firebase-cloud-messaging google-cloud-functions