-1

This is how my html looks like

<!DOCTYPE html>
<html>
<head>
<title>Pet Article</title>

<script src="https://www.gstatic.com/firebasejs/5.5.8/firebase.js"></script>

</head>



<body>

 
 <img src = "cat.jpg" width = 700px , height = "500px" />
 <img src = "dog.jpg" width = 700px , height = "500px" />

 <p>This is the paragraph <br /> Need more?</p>
 <hr />
 
 <h1 id="big0ne" ></h1> 
 
 <script>
  // Initialize Firebase
  var config = {
    apiKey: "",
    authDomain: "",
    databaseURL: "",
    projectId: "",
    storageBucket: "",
    messagingSenderId: ""
  };
  firebase.initializeApp(config);
  
  var big0ne = document.getElementById('big0ne');
  var dbRef = firebase.database().ref().child('text');
  dbRef.on('value', snap => big0ne.innerText = snap.val());
   
</script>
 
</body>
</html>

I am a newbie in programming and this is the first time I would ask here so please bear with me.

We were asked to make a project using firebase database and connect it to our website to retrieve data. I have found tutorials on youtube and the internet, however i cant seem to find a tutorial that works on retrieving nested value on firebase. It returns the data as [object Object]

I would like to know how to retrieve nested data in firebase. I would attach the image of how my database looks like. heres my html code. I didnt make a separate javascript file. I just put the javascript code inside the "script" tag since it works anyways. I will purposely remove API keys, etc. for security reasons.

Lancer EX
  • 37
  • 7

1 Answers1

1

You right now have the following code to read from Firbase:

var dbRef = firebase.database().ref().child('text');
dbRef.on('value', snap => big0ne.innerText = snap.val());

This reads the value of the text node and you then take its value with val(). Looking at the JSON screenshot you shared, the value of text is:

{
  "text2": "Wonder Pets"
}

This is itself a JavaScript object, so if you call toString() on it (which your code implicitly does) you get "[object Object]" (or some variant of that, depending on the browser).

To get the value of the text2 child node, you should use:

big0ne.innerText = snap.child("text2").val()

So in the above line, we take the text2 child node of the snapshot and then value of that, which is exactly the string you want.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Thanks alot this worked. What will I do if for example text2 has another child node? For Example "text>text2>text3 : Wonder Pets"... and so on? Basically I'm asking what will I use if I need more nested data such as "text 4 or text 5". – Lancer EX Nov 19 '18 at 13:58
  • `snap.child("text2").child("text3").val()` or `snap.child("text2/text3").val()`, etc – Frank van Puffelen Nov 19 '18 at 15:08