2

I have a problem retrieveing data from firebase database. The data structure is like this:

posts:{ 
    (Random key):{
       post:{
           text: "random text"
           title: "title of some kind"
           username: "username"
       }
  }
}

and the code I tried to retrieve text is:

database.ref("posts").orderByChild("post").on('value', function(snapshot){
       console.log(snapshot.val().text);
   }) 

I am new to this firebase thing, so i am sorry if it's a stupid question.

2
  • 1
    post is not a direct child of posts, so you cannot orderByChild() of that nested property. Commented Sep 15, 2019 at 1:34
  • okay but how can I fix it? @AlexanderStaroselsky Commented Sep 15, 2019 at 1:39

2 Answers 2

1

You have to change your code like this:

database.ref("posts").child(randomKey).on('value', function(snapshot){
       console.log(snapshot.child("post").child("text").val());
   }) 

Your snapshot is a DataSnapshot and it contains a child() method that is a DataSnapshot itself. To get your text field you just have to use chield("text") and get then the val().

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

4 Comments

It gives me value of null
oh saw your Random key part. I will edit my answer
how do i define that randomKey part? I have no idea how to get that, these are automatically created by firebase on saving data
Are you trying to get every value of your text field or just a single one?
1

First you can sort the result by using orderBy on any attributes on post. For example


var sortedpost = firebase.database().ref('posts').orderByChild('post/text');

Or simply you can also use orderByKey to sort based on the document ID.

After this you can get the result you are looking for using on listener as below.

    sortedpost.on('value', function(snapshot){
       console.log(snapshot.val());
   }) 

3 Comments

But how can i bypass that random key part? because post is random keys child.
It will look into the nested child by itself. And why don't you add some meaningfull docID which can be done at the time of adding any data in firebase
docID is different for every post ( which should be :p) so you cannot just create a hard coded path for it, and if you want to sort the data based on the docID itself then you can use orderBykey()

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.