【问题标题】:Realtime Database onWrite triggers in Cloud Functions has null val() dataCloud Functions 中的实时数据库 onWrite 触发器具有 null val() 数据
【发布时间】:2018-10-01 22:21:25
【问题描述】:

我正在尝试使用 firebase 中的云函数实现推送通知触发器,但每次尝试 val 函数都返回 null。它无法识别 pushID,我使用 push() 方法从 android 实现了数据库。 这是我的数据库结构

这是我创建帖子时推送通知的代码。

  //import firebase functions modules
const functions = require('firebase-functions');
//import admin module
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);


// Listens for new messages added to messages/:pushId
exports.pushNotification = functions.database.ref('/Posts/Posts/{pushId}').onWrite( event => {

    console.log('Push notification event triggered');

    //  Grab the current value of what was written to the Realtime Database.
    var valueObject = event.data.val();

    // if(valueObject.photoUrl != null) {
    //   valueObject.photoUrl= "Sent you a photo!";
    // }

  // Create a notification
    const payload = {
        notification: {
            title:valueObject.tittle,
            body: valueObject.details,
            sound: "default"
        },
    };

  //Create an options object that contains the time to live for the notification and the priority
    const options = {
        priority: "high",
        timeToLive: 60 * 60 * 24
    };


    return admin.messaging().sendToTopic("pushNotifications", payload, options);
});

这是云功能控制台中的错误

使用 OnCreate 后编辑:-

   exports.pushNotification = functions.database.ref('/Posts/Posts/{pushid}').onCreate((snap, context) => {

const original = snapshot.val();
    console.log('Push notification event triggered');

    //  Grab the current value of what was written to the Realtime Database.
    // var valueObject = event.data.val();
 var valueObject = snap.val();
    // if(valueObject.photoUrl != null) {
    //   valueObject.photoUrl= "Sent you a photo!";
    // }

  // Create a notification
    const payload = {
        notification: {
            title:valueObject.tittle,
            body: valueObject.details,
            sound: "default"
        },
    };

【问题讨论】:

    标签: javascript android firebase firebase-cloud-messaging google-cloud-functions


    【解决方案1】:

    您的代码似乎尚未适应新的 Functions 1.0 SDK。此处详细说明了差异:https://firebase.google.com/docs/functions/beta-v1-diff

    正如您从 Realtime Database section 中的该文档中看到的那样,onWrite 触发器现在为您提供了一个带有 beforeafter 属性的 Change 对象,您可以使用这些属性在更新之前或之后获取数据库位置的值。

    还要考虑你是否真的想要一个 onCreate 触发器,它更容易处理,并且只在匹配位置的数据被新创建时触发一次。

    【讨论】:

    • 感谢您的回复,我已经更新了我的代码,现在我正在使用 onCreate。但现在它在我的标题字段上返回 null,错误:函数执行失败。详细信息:无法读取 null 的属性“标题”。但是在我的数据库中,我的帖子确实有一个标题属性。似乎问题出在 {pushId} 上,我想我似乎无法将 push Key 作为孩子或作为参考来恢复。 pushId 是用于恢复推送项目的唯一通配符吗?我在我的 android 代码中使用了 push() 方法。
    • 如果您有与第一个不同的后续问题,请单独解释和说明新问题。
    猜你喜欢
    • 2017-08-25
    • 2018-01-26
    • 2017-10-18
    • 2018-05-02
    • 2018-10-11
    • 2020-08-24
    • 2021-11-17
    • 2018-08-09
    • 2017-12-13
    相关资源
    最近更新 更多