【问题标题】:Firebase Cloud function event - sometime not getting data on update eventFirebase Cloud 函数事件 - 有时无法获取更新事件的数据
【发布时间】:2018-10-08 22:44:42
【问题描述】:

我已经编写了 firebase 云函数来触发更新记录。有时我没有得到相同的更新记录。我在下面添加我的代码。请检查附件图片。

exports.onNotificationUpdate = functions.database.ref('/Notification/{userId}/{notificationId}/userResponse').onUpdate(event => {
    return admin.database().ref(`/Notification/${event.params.userId}/${event.params.notificationId}`).once('value').then(function (snapshot) {
        var notification = snapshot.val();

        if (!notification) {
            console.error("Notification not found on notification update");
            return;
        };

我也可以从父级获取 Notification 对象,但我想知道问题的最佳方法和此代码的问题。

this is error log

this is database structure

这是我在这里的第一篇文章,如果需要更多信息,请告诉我。 谢谢

【问题讨论】:

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


    【解决方案1】:

    您不必在函数中调用once,因为它已经在您正在侦听的位置返回数据,只需侦听父节点即可。

    所以你应该这样做:

    exports.onNotificationUpdate = functions.database.ref('/Notification/{userId}/{notificationId}').onUpdate(event => {
            const notification = event.data.val(); 
    
            if (notification === null) {
                console.error("Notification not found on notification update");
                return null;
                //actually this would only be called in case of deletion of the Notification
            } else {
                //do something with the notification data: send Android notification, send mail, write in another node of the database, etc.
               //BUT return a Promise
               //notification const declared above is a JavaScript object containing what is under this node (i.e. a similar structure than your database structure as shown in the image within your post.)
            }
    });
    

    我建议您观看 Firebase 团队的这三个视频:

    https://www.youtube.com/watch?v=7IkUgCLr5oA&t=517s

    https://www.youtube.com/watch?v=652XeeKNHSk&t=27s

    https://www.youtube.com/watch?v=d9GrysWH1Lc

    另外,请注意 Cloud Functions 已更新,如果您使用 1.0.0 以上的 CF 版本,您的代码的第一行应以不同的方式编写。见https://firebase.google.com/docs/functions/beta-v1-diff

    【讨论】:

    • 非常感谢,请参阅我需要此 /Notification/{userId}/{notificationId}/ 通知变量中的对象而不是 /Notification/{userId}/{notificationId}/userResponse。我在 /Notification/{userId}/{notificationId}/userResponse 上添加了更新事件。我得到了你的答案,我应该通过家长电话获得通知吗?
    • 不,你应该在父节点级别监听,即/Notification/{userId}/{notificationId}。我已经更新了我的答案。另外,我允许自己坚持:看看这 3 个视频(至少是前 2 个),对于开始使用 Cloud Functions 的任何人来说,它们都是必须的。这不是浪费时间,而是真正的投资。
    • 您有时间查看此解决方案吗?您可以考虑接受,谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-24
    • 1970-01-01
    • 2018-01-19
    • 2021-09-27
    • 2019-08-18
    • 1970-01-01
    相关资源
    最近更新 更多