Ошибка облачной функции firebase TypeError: Невозможно прочитать свойство 'child' из undefined - PullRequest
0 голосов
/ 18 апреля 2020

Я новичок в облачной функции 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.

enter image description here

И полная Stacktrace от logcat здесь.

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'

1 Ответ

1 голос
/ 18 апреля 2020

Обратите внимание, что обработчик onWrite() принимает объект Change , который имеет свойства before & after, но не data. Я предполагаю, что это является причиной проблемы, см. onWrite() документация . Если вы хотите получить обновленные данные, используйте 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();
  ...
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...