0

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?

1
  • @Dravidian javascript Commented Sep 11, 2016 at 8:35

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @Frank van Puffelen; it worked for me but how to store value of nos. of records.
Has the on function deprecated? It cannot resolve symbol on for me.
2

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);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.