firebase cloud function error TypeError: Cannot read property 'child' of undefined

firebase cloud function error TypeError: Cannot read property 'child' of undefined

我是 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'

请注意 onWrite() 处理程序接受 Change object which has before & after properties, but not data. I guess it's the cause of the problem, see 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();
  ...
});