Ravindra Gupta
Ravindra Gupta

Reputation: 73

how to get firebase database nested data access inside unique key

In firebase I want to access database written as below.

enter image description here

<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 i.e. userid , but I want to access data inside that key which I don't know as it will be generated for next post automatically.

How to access nested data inside key?

Upvotes: 0

Views: 2523

Answers (2)

Frank van Puffelen
Frank van Puffelen

Reputation: 599131

As an alternative to Callam's answer, you can also keep using the value event. But in that case you must loop over the messages with 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. 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.

Upvotes: 2

Callam
Callam

Reputation: 11539

You want the child_added event type, this will log the snapshot of every child under your ref.

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

Upvotes: 2

Related Questions