无法读取未定义的属性“ val”

时间:2019-08-17 19:51:51

标签: javascript firebase-realtime-database google-cloud-functions

我尝试学习如何使用Firebase函数发送通知。因此,我使用以下示例代码:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendAdminNotification = functions.database.ref('/message').onWrite(event => {
const news = event.data.val();
     const payload = {notification: {
         title: 'New news',
         body: `${news.title}`
         }
     };
return admin.messaging().sendToTopic("News",payload)
    .then(function(response){
         return console.log('Notification sent successfully:',response);
    }) 
    .catch(function(error){
         console.log('Notification sent failed:',error);
    });

});

但是它给了我一个错误: Cannot read property 'val' of undefined 我一直在寻找解决方案,尝试过this,但还是不行...

任何建议将不胜感激。

1 个答案:

答案 0 :(得分:3)

我认为您没有使用文档中指定的语法。

请参阅this文档。

无论如何,正如我在上面链接的文档中看到的那样,您的代码应为:

exports.sendAdminNotification = functions.database.ref('/message')
    .onWrite((change, context) => { 
        console.log(change);
        // Do something with change or context
    });
相关问题