简体   繁体   English

如何在唯一密钥内获取Firebase数据库嵌套数据访问

[英]how to get firebase database nested data access inside unique key

In firebase I want to access database written as below. 在firebase中,我要访问如下编写的数据库。

在此处输入图片说明

<script>
function fnReadMails(){
  var user = firebase.auth().currentUser;
  var ref = firebase.database().ref('/posts/'+user.uid);
  ref.on("value", function(snapshot) {
    var vardata = (snapshot.val());
    console.log(vardata);
  });
}
</script>

The problem is that string marked in red is unique push key randomly generated. 问题是用红色标记的字符串是随机生成的唯一按键。 Whenever I am getting a reference I am able to take ref up to one level upper ie userid , but I want to access data inside that key which I don't know as it will be generated for next post automatically. 每当获得参考时,我都可以将参考提升到上一层,即userid ,但是我想访问该键中的数据,我不知道,因为它将自动为下一篇文章生成。

How to access nested data inside key? 如何访问键内的嵌套数据?

You want the child_added event type, this will log the snapshot of every child under your ref. 您需要child_added事件类型,这将记录您的引用下每个孩子的快照。

ref.on("child_added", function(snapshot) {
    console.log(snapshot);
});

As an alternative to Callam's answer, you can also keep using the value event. 作为Callam答案的替代方法,您还可以继续使用value事件。 But in that case you must loop over the messages with forEach() : 但是在那种情况下,您必须使用forEach()遍历消息:

ref.on("value", function(snapshot) {
  snapshot.forEach(function(messageSnapshot) {
    console.log(messageSnapshot.val());
  }
});

Both approaches (using value vs using child_* ) result in the same network traffic. 两种方法(使用value与使用child_* )导致相同的网络流量。 But using value is often easier to get started with, while using child_ events makes it easier to update the specific UI element that needs to be updated. 但是,使用value通常更容易上手,而使用child_事件则使更新需要更新的特定UI元素更加容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM