【问题标题】:firebase onUpdate function is not triggeringfirebase onUpdate 功能未触发
【发布时间】:2020-10-20 07:04:25
【问题描述】:

当我的数据结构中的计数变量发生变化时,我尝试触发 .onUpdate 函数。尽管计数变量更改仍然没有触发功能。 我的计数变量低于主实时数据库。

const functions = require('firebase-functions');
    
// The Firebase Admin SDK to access Cloud Firestore.
const admin = require('firebase-admin');
admin.initializeApp();

exports.cleanStorage=functions.database
    .ref('/count')
    .onUpdate((change,context)=>{
    
    
    if(change.before.count===change.after.count){
    return null;
     }
    
     const newCount=change.after.count-7;
    
    
    return change.after.ref.update({count:newCount});
});

【问题讨论】:

  • 您尝试console.logchange.before.count 看看它返回了什么?

标签: javascript node.js firebase firebase-realtime-database google-cloud-functions


【解决方案1】:

正如 Prashin Jeevaganth 在他的评论中提到的,您应该调试您的代码。你会看到change.before.countchange.after.countundefined,这就解释了为什么什么都没发生。

看看doc:你需要使用val()方法如下:

exports.cleanStorage = functions.database
    .ref('/count')
    .onUpdate((change, context) => {

        if (change.before.val() === change.after.val()) {
            return null;
        }

        const newCount = change.after.val() - 7;

        return change.after.ref.parent.update({ count: newCount });
    });

重要提示:请注意,使用此代码您可能会进入无限循环,因为您将更新节点,这将触发 Cloud Function。您可以更新另一个节点,例如:

return change.after.ref.child('newCount').update({ count: newCount });

【讨论】:

    【解决方案2】:

    根据the referencebeforeafter都返回DataSnapshot。这意味着如果你想要获取值,你必须使用 'val()'。

    由于上述代码示例中的if 语句将始终为undefined===undefined,解析为true,因此该函数将始终返回null

    我没有操场来测试它,但我会尝试将 if 语句更改为:

    if(change.before.val() == change.after.val())

    可能还有更多方法可以做到...希望对您有所帮助!

    【讨论】:

      猜你喜欢
      • 2021-04-08
      • 2021-08-16
      • 1970-01-01
      • 1970-01-01
      • 2021-11-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多