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
这是索引.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中部署时,LOG中的函数显示:
The above code is misconfigured, when I deploy in Node.js, LOG in Function shows:
TypeError:无法读取未定义的属性'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/functions/beta-v1 -diff#realtime-database
云功能已更改,现在 onWrite
有两个参数更改
和上下文
The cloud functions were changed and now onWrite
has two parameters change
and context
更改
在之前有两个属性,在
之后有,并且每个属性都是
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/reference/admin/node/admin.database.DataSnapshot
这篇关于Firebase TypeError:无法读取未定义的属性“val”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!