Firebase TypeError:无法读取未定义的属性“val" [英] Firebase TypeError: Cannot read property 'val' of undefined
问题描述
我已经尝试使用 Firebase 云功能发送通知.我的项目结构
I have tried Firebase cloud function for sending a notification.My project structure
这是 index.js,
and this is the index.js,
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.pushNotification = functions.database.ref('/messages').onWrite( event => {
console.log('Push notification event triggered');
const message = event.data.val();
const user = event.data.val();
console.log(message);
console.log(user);
const topic = "myTopic";
const payload = {
"data": {
"title": "New Message from " + user,
"detail":message,
}
};
return admin.messaging().sendToTopic(topic, payload);
});
以上代码配置错误,在Node.js中部署时,Function中的LOG显示:
The above code is misconfigured, when I deploy in Node.js, LOG in Function shows:
类型错误:无法读取未定义的属性‘val’".
"TypeError: Cannot read property 'val' of undefined".
实际上我想做什么:我试图从快照加载中提取信息到那个 index.js 中,这样当一个新的孩子被添加到实时数据库时,它应该触发一个带有标题和正文的通知负载.
What Actually I am trying to do : I am trying to extract info from snapshot load into that index.js so that when a new child gets added to Real-time database, it should trigger a notification payload with a title and body.
在Android中,我使用了一个子监听器,用于在添加新记录时进行监听
In Android, I use a child listener, for listening when a new record is added
FirebaseDatabase.getInstance().getReference().child("messages")
OnChildAdded(.....){
if (dataSnapshot != null) {
MessageModel messageModel = dataSnapshot.getValue(MessageModel.class);
if (messageModel != null) {
// do whatever
}
}
但是在 index.js 中,我无法解析它.非常感谢如何根据我的数据库结构固定 index.js 的一些指导.PS-我从来没有用 JS 写过代码如果您需要更多背景信息,我很乐意提供.
But in index.js, I could not able to parse that. A bit guidance how to fixate index.js according to my database structure would be immensely appreciated. PS- I have never done coding in JS If you want more context, I'd be happy to provide it.
推荐答案
改变这个:
exports.pushNotification = functions.database.ref('/messages').onWrite( event => {
const message = event.data.val();
const user = event.data.val();
});
为此:
exports.pushNotification = functions.database.ref('/messages').onWrite(( change,context) => {
const message = change.after.val();
});
请检查:
https://firebase.google.com/docs/函数/beta-v1-diff#realtime-database
云函数改变了,现在onWrite
有两个参数change
和context
The cloud functions were changed and now onWrite
has two parameters change
and context
change
有两个属性 before
和 after
,每个属性都是一个 DataSnapshot
,其中列出了方法这里:
The change
has two properties before
and after
and each of these is a DataSnapshot
with the methods listed here:
https://firebase.google.com/docs/参考/admin/node/admin.database.DataSnapshot
这篇关于Firebase TypeError:无法读取未定义的属性“val"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!