firebase云函数错误TypeError:无法读取未定义的属性“子”

Posted

技术标签:

【中文标题】firebase云函数错误TypeError:无法读取未定义的属性“子”【英文标题】:firebase cloud function error TypeError: Cannot read property 'child' of undefined 【发布时间】:2020-08-01 02:02:25 【问题描述】:

我是firebase云功能的新手,我的情况是每当数据库中发布新文章时,我需要向我的应用用户显示通知。

我的代码

var functions = require('firebase-functions');
var admin = require('firebase-admin');


admin.initializeApp(functions.config().firebase);
exports.sendNotification = functions.database.ref('/article/articleId')
.onWrite((event:  data: any; ) => 
        var eventSnapshot = event.data;
        var str1 = "Author is ";
        var str = str1.concat(eventSnapshot.child("author").val());
        console.log(str);

        var topic = "android";
        var payload = 
            data: 
                title: eventSnapshot.child("title").val(),
                author: eventSnapshot.child("author").val()
            
        ;


        return admin.messaging().sendToTopic(topic, payload)
            .then(function (response: any) 

                console.log("Successfully sent message:", response);
            )
            .catch(function (error: any) 
                console.log("Error sending message:", error);
            );
        );

这是我在 Firebase 中的数据库结构。

来自 logcat 的完整 Stacktrace 在这里。

TypeError: Cannot read property 'child' of undefined
    at exports.sendNotification.functions.database.ref.onWrite (/srv/lib/index.js:17:41)
    at cloudFunction (/srv/node_modules/firebase-functions/lib/cloud-functions.js:131:23)
    at /worker/worker.js:825:24
    at <anonymous>
    at process._tickDomainCallback (internal/process/next_tick.js:229:7)

sendNotification
Function execution took 286 ms, finished with status: 'error'

【问题讨论】:

您正在使用旧版本的 Cloud Functions API。如果您正在学习教程,那么它已经过时了。我建议使用产品文档来了解它是如何工作的。 firebase.google.com/docs/functions/database-events 【参考方案1】:

请注意,onWrite() 处理程序接受具有beforeafter 属性的Change 对象,但不接受data。我想这是问题的原因,请参阅onWrite()documentation。如果您想获取更新的数据,请使用 event.after.child('author') 而不是 event.data.child('author')

exports.sendNotification = functions.database.ref('/article/articleId').onWrite(change => 
  // Exit when the data is deleted.
  if (!change.after.exists()) 
      return null;
  

  const author = change.after.child('author').val();
  ...
);

【讨论】:

@SathishkumarG 很高兴为您提供帮助!还要注意如果文件被删除change.after可能不存在,所以最好检查一下。我也更新了答案。

以上是关于firebase云函数错误TypeError:无法读取未定义的属性“子”的主要内容,如果未能解决你的问题,请参考以下文章

无法在本地测试云功能,模拟器无法启动 TypeError: _onRequestWithOpts is not a function

找不到模块:错误:无法解析“流”或 TypeError:stream.Readable 不是构造函数

Nuxt 抛出错误:未捕获的 TypeError:无法将类作为函数调用

错误:TypeError:对象没有方法“设置”

Firebase 函数 - 发送推送并收到错误消息“TypeError:无法将未定义或 null 转换为对象”[关闭]

Cloud Functions 错误:函数返回未定义、预期的 Promise 或值,以及 TypeError:无法读取未定义的属性“First_Name”