Firebase函数的getChild值 [英] Firebase functions getChild value

查看:78
本文介绍了Firebase函数的getChild值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在firebase功能上有问题.我想做的是更新Items的子项时,然后我想获取Count的值并进行进一步的计算,但是我所面临的是,firebase日志控制台始终显示错误信息"TypeError:无法读取属性'val'的".

I am having a problem on firebase functions. What I trying to do is when Items's child gets updated, then I want to get the value of Count and do further calculation, But what I am facing is that the firebase log console always shows an erreor "TypeError: Cannot read property 'val' of undefined".

JSON结构

"VTEST" : {
    "A" : {
      "Count" : 5,
      "Items" : {
        "item1" : "apple"
      },
      "NUMBER" : 5
    },
    "B" : {
      "Count" : 8,
      "Items" : {
        "item1" : "orange;"
      },
      "NUMBER" : 3
    },
    "C" : {
      "Count" : 10,
      "Items" : {
        "item1" : "grape"
      },
      "NUMBER" : 7
    },
    "D" : {
      "Count" : 12,
      "Items" : {
        "item1" : "grava"
      },
      "NUMBER" : 10
    },
    "E" : {
      "Count" : 15,
      "Items" : {
        "item1" : "fish"
      },
      "NUMBER" : 12
    },
    "F" : {
      "Count" : 18,
      "Items" : {
        "item1" : "chicken;"
      },
      "NUMBER" : 8
    }
  }

我的代码:

exports.ItemCount = functions.database.ref('/VTEST/{ID}/Items').onUpdate((updateRef, context) => {
        var childCount = updateRef.after.numChildren();
        var newReference = updateRef.after.ref.parent.child('/Count');
        var Count = newReference.val();
        Count = Count + childCount;
        return updateRef.ref.update({Count})
    })

我期望的是Count的值将被更新,但它始终显示错误:"TypeError:无法读取未定义的属性'val'" 谁能告诉我我在做什么错,我不明白.

What I expect is the Count's value will be update, but it always show error : "TypeError: Cannot read property 'val' of undefined" Can anyone tell me what am I doing wrong here, I don't get it.

推荐答案

问题来自 once() 方法获取相应数据库位置的值.

The problem comes from the fact that a Reference does not have a val() method. You need to use the once() method to get the value of the corresponding database location.

以下改编的代码应该可以工作:

The following adapted code should work:

exports.ItemCount = functions.database
  .ref('/VTEST/{ID}/Items')
  .onUpdate((updateRef, context) => {
    var childCount = updateRef.after.numChildren();
    var newReference = updateRef.after.ref.parent.child('/Count');
    return newReference.once('value').then(dataSnapshot => {
      var Count = dataSnapshot.val();
      Count = Count + childCount;
      return newReference.parent.update({ Count: Count });
    });
  });

但是,根据您的确切要求,您可以决定使用交易,请参见 https://firebase.google.com/docs/database/web/read-and-write#save_data_as_transactions

However, depending on your exact requirements, you may decide to use a Transaction, see https://firebase.google.com/docs/database/web/read-and-write#save_data_as_transactions

这篇关于Firebase函数的getChild值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆