【问题标题】:child_changed event firebasechild_changed 事件火力库
【发布时间】:2017-03-15 20:32:26
【问题描述】:

我对 firebase 有点陌生。当我遇到它的一些事件时,我只是在尝试一些例子,顺便说一句,这些事件很酷。

我在 firebase 数据库中保存了一些数据:

 driver
      -KV_Cj7sL6sg6K9E5ifh
         status: "Incomplete"

困扰我的是,当一个孩子被更新时,child_changed 事件被触发。当我访问它的数据时,我没有看到它的密钥。

我在驱动表中创建了一个节点(我认为行在 firebase 中称为节点不确定)。当我更改它的状态以完成它触发的 child_changed 事件时。我收到了已更新的数据包。问题是我也想获得 Id(KV_Cj7sL6sg6K9E5ifh)。但问题是它只向我发送状态:完成。

这是我为 child_changed 编写的代码:

usersRef.on("child_changed", function(data) {
   var player = data.val();
   console.log(player);
   console.log("The new status is:  "+ player.status);
});

请帮助我,我将如何接收 ID。谢谢

【问题讨论】:

标签: node.js express firebase firebase-realtime-database


【解决方案1】:

您所说的 id,在 Firebase 术语中称为 key。要获取快照的密钥,您可以访问该快照的key 属性:

usersRef.on("child_changed", function(snapshot) {
   var player = snapshot.val();
   console.log(player);
   console.log("The new status is:  "+ player.status);
   console.log("The key of the player is "+snapshot.key);
})

【讨论】:

  • 我知道。我尝试使用密钥,但这对我不起作用。这才是真正让我感到惊讶的原因,因此我来到了这里
  • 弗兰克它开始像你说的那样为我工作。我试图找出问题所在,但没有发现任何问题。重新启动我的电脑,我得到了你告诉我的钥匙。真的很奇怪。
  • 很高兴听到你把它整理好了。
【解决方案2】:

你可以得到Id孩子,试试下面

console.log("The new status is:  "+ player.$id);

Firebase 返回的每个Object 都包含$id 属性

更新:

你可以得到id/key,即使Firebase不返回孩子的id,试试下面

console.log("The new status is:  "+ data.ref.key); //it will returns -KV_Cj7sL6sg6K9E5ifh


console.log("The new status is:  "+ data.ref.parent.key); //it will returns driver

【讨论】:

  • 说它给了我不确定的。这是我使用它的方法usersRef.on("child_changed", function(data) { var player = data.val(); console.log("The new status is: "+ player.status); console.log("The new Id is: "+ player.$id); });
  • console.log(player) 的输出是什么?
  • 说它是未定义的
  • 奇怪,它给console.log(player) 是未定义的?那么你如何获得状态。它不能是未定义的
  • Zaid player.status 让我完成,因为我已将状态从不完整更改为完成,但播放器本身给我未定义。
猜你喜欢
  • 1970-01-01
  • 2021-06-05
  • 2016-09-17
  • 1970-01-01
  • 1970-01-01
  • 2017-07-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多