title: How to access parent of child node in Firebase Realtime Database?
body: <p><a href="https://i.stack.imgur.com/GW78z.png" rel="nofollow noreferrer">My Firebase Database Image </a>In Firebase's Realtime Database, I am trying to access the name of the parent node being given the name of the child node. However, .parent seems to require a reference to the child node, which I can't seem to get without the name of the parent node.</p>
  
  <p>This is the code for my data:</p>
  
  <p></p>
  
  <pre><code>&lt;script src="https://www.gstatic.com/firebasejs/5.7.3/firebase.js"&gt;&lt;/script&gt;
  &lt;script src="https://apis.google.com/js/platform.js" async defer&gt;&lt;/script&gt;
  
  &lt;style&gt;
      tr:hover {background-color: #f5f5f5;}
      th, td {
          border-bottom: 1px solid #ddd;
      }
  
  &lt;/style&gt;
  &lt;script&gt;
  
      // Initialize Firebase
  </code></pre>
  
  <p>var config = {
      apiKey: "AIzaSyA85okZdA9v_XAa9BgJJ2EOdUEbL09k0uY",
      authDomain: "fir-test-bcb6d.firebaseapp.com",
      databaseURL: "<a href="https://fir-test-bcb6d.firebaseio.com" rel="nofollow noreferrer">https://fir-test-bcb6d.firebaseio.com</a>",
      projectId: "fir-test-bcb6d",
      storageBucket: "fir-test-bcb6d.appspot.com",
      messagingSenderId: "976121809263"
    };
    firebase.initializeApp(config);</p>
  
  <pre><code>    // Check to see if you are logged in
      firebase.auth().onAuthStateChanged(function(user) {
          if (user == null) {
              alert("Not logged in.");
              return;
          } else {
              userId = user.uid;
              name = user.displayName;
              imageUrl = user.photoURL;
              email = user.email;
              var user = firebase.auth().currentUser;
              var newuser = user.getAdditionalUserInfo
  
              user.sendEmailVerification().then(function() {
              // Email sent.
              }).catch(function(error) {
              // An error happened.
              });
              if (firebase.auth().currentUser.emailVerified) {
                  alert('Email Verified');
                  console.log('Email Verified');
              }
  
              // write user data to users
              //writeUserData(userId, name, email, imageUrl);
              // moved to tweet function
  
              // write data to document
              mydiv = document.getElementById("mydata");
              mydiv.innerHTML = name
              myphotodiv = document.getElementById("myphoto");
              myphotodiv.innerHTML = "&lt;img src='" + imageUrl + "'/&gt;";
  
              firebase.database().ref('/tweets').once('value').then(function(snapshot) {
                  var data = (snapshot.val());
                  if (data == null) {
                    console.log("No data found at /tweets/" + userId);  
                  } else {
  
                    firebase.database().ref('/users').once('value').then(function(snapshot) { 
                      var userdata = (snapshot.val());
                      if (userdata != null) {
                         dataarray = [data,userdata]
                         console.log(dataarray)
                         updatetweets(dataarray); 
                      }
                    });
                    //console.log(data)
                    //updatetweets(data);
                  }
              });
          } // end user null check
      }); // end check auth state
  
      function encodeImageFileAsURL() {
  
          var filesSelected = document.getElementById("inputFileToLoad").files;
          if (filesSelected.length &gt; 0) {
              var fileToLoad = filesSelected[0];
              var fileReader = new FileReader();
              fileReader.onload = function(fileLoadedEvent) {
                  var srcData = fileLoadedEvent.target.result; // &lt;--- data: base64
                  //var newImage = document.createElement('img');
                  //newImage.src = srcData;
                  //document.getElementById("imgTest").innerHTML = newImage.outerHTML;
                  document.getElementById("imgTest").innerHTML = srcData;
                  //console.log("Converted Base64 version is: " + document.getElementById("imgTest").innerHTML);
                  //console.log(srcData);
              }
              fileReader.readAsDataURL(fileToLoad);
          }
      } // end function
  
      // write user data
      function writeUserData(userId, name, email, imageUrl) {
          firebase.database().ref('users/' + userId).once('value',    function(snapshot) {
               if (!snapshot.exists()) {
                  firebase.database().ref('users/' + userId).set({
                      username: name,
                      email: email,
                      profile_picture : imageUrl
                  }); 
               }                                      
          });
      }
  
  
      function updatetweets(data) {
          var tweetnumber = 0;
          //var mylist = "&lt;ul&gt;";
          var mytab = "&lt;table id='tweettable'&gt;";
          users = data[1]; // put on top, because changed data - not good coding change later
          data = data[0];
  
  
          for (var u in data) {
              for (var t in data[u]) {
                  mytab = mytab + "&lt;tr&gt;";
                  var date = new Date(data[u][t].time);
                  var time = date.toString();                    
                  if (data[u][t].img != "") {
                      mytab = mytab + "&lt;td&gt;&lt;img src='" + users[u].profile_picture + "' width='50px'&gt;&lt;/td&gt;";
                      mytab = mytab + "&lt;td&gt;" + users[u].email + "&lt;/td&gt;";
                      mytab = mytab + "&lt;td&gt;" + data[u][t].tweet + "&lt;/td&gt;";
                      mytab = mytab + "&lt;td&gt;" + time + "&lt;br&gt;&lt;img src='" + data[u][t].img + "' width='300px'&gt;&lt;/td&gt;";
                      mytab = mytab + "&lt;td&gt;&lt;p&gt;Like this tweet&lt;/p&gt;" + "&lt;button id=" + t + " onclick=" + "like(this.id)" + "&gt;Like&lt;/button&gt;" + "&lt;p&gt;Likes: &lt;/p&gt;" + "&lt;p id='" + t + "likes'" + "'&gt;" + data[u][t].likes + "&lt;/p&gt;" + "&lt;/td&gt;";
  
                  } else {
                      mytab = mytab + "&lt;td&gt;&lt;img src='" + users[u].profile_picture + "' width='50px'&gt;&lt;/td&gt;";
                      mytab = mytab + "&lt;td&gt;" + users[u].email + "&lt;/td&gt;";
                      mytab = mytab + "&lt;td&gt;" + data[u][t].tweet + "&lt;/td&gt;";
                      mytab = mytab + "&lt;td&gt;" + time + "&lt;/td&gt;";
                      mytab = mytab + "&lt;td&gt;&lt;p&gt;Like this tweet&lt;/p&gt;" + "&lt;button id=" + t + " onclick=" + "like(this.id)" + "&gt;Like&lt;/button&gt;" + "&lt;p&gt;Likes: &lt;/p&gt;" + "&lt;p id='" + t + "likes'" + "'&gt;" + data[u][t].likes + "&lt;/p&gt;" + "&lt;/td&gt;";
                  } 
                  mytab = mytab + "&lt;/tr&gt;";
              }   
          }
          //mylist = mylist + "&lt;/ul&gt;";
          mytab = mytab + "&lt;/table&gt;"
          var mytdiv = document.getElementById("mytweets");
          //mytdiv.innerHTML = mylist;
          mytdiv.innerHTML = mytab;
      }
  
      // write tweets to firebase
      function tweet() {
  
          var twitdoc = document.getElementById("twit");
          var twitimg = document.getElementById("imgTest");
          var nameValue = twitdoc.value;
          var imgValue = twitimg.innerHTML;
          var d = new Date();
          var dayofweek = d.getDay();
          console.log(dayofweek);
          var weekdays = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
          var dayofmonth = d.getDate();
          var monthnumber = d.getMonth();
          var monthnames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
          var year = d.getFullYear();
          var thedate = weekdays[dayofweek] + ", " + monthnames[monthnumber] + " " + dayofmonth + ", " + year;
          console.log(thedate);
          var hours = d.getHours();
          var minutes = d.getMinutes();
          if (hours &lt; 12) {
              var time = 
          }
          var js_time = Date.now();
          //var numberoffollowers = 2;
          var tweetid = firebase.database().ref('tweets/' + userId + "/").push({tweet: nameValue, time: js_time, date: thedate, img: imgValue, likes: 0});
          //var followers = firebase.database().ref('users/' + userId + "/").push({followers: numberoffollowers});
          twitdoc.value = "";
          writeUserData(userId, name, email, imageUrl);
          console.log("tweet written")
  
          firebase.database().ref('/tweets').once('value').then(function(snapshot) {
                  var data = (snapshot.val());
                  if (data == null) {
                    console.log("No data found at /tweets/" + userId);  
                  } else { 
                      firebase.database().ref('/users').once('value').then(function(snapshot) { 
                      var userdata = (snapshot.val());
                      if (userdata != null) {
                         dataarray = [data,userdata]
                         console.log(dataarray)
                         updatetweets(dataarray); 
                      }
                    });
                  }
              });
  
  
  
          // The unique key stored in tweetid is based on a timestamp, so list items will automatically be ordered chronologically. Because Firebase generates a unique key for each tweet, no write conflicts will occur if multiple users add a post at the same time. https://firebase.google.com/docs/database/admin/save-data
  
      }
  
      function like(t) {
          alert(t);
          console.log('tvalue' + t);
          console.log(t.ref());
  
          var y = firebase.database().ref('/tweets/' + userId + "/" + t);
          var parent = y.parent;
          console.log('Parent: ' + parent);
          var res = String(parent);
          console.log(res);
          var goal = res.substring((res.length - 28), res.length);
          console.log(goal);
  
  
  
          var oldlikes = document.getElementById(t + "likes").innerHTML;
          console.log(oldlikes);
          firebase.database().ref('/tweets/' + goal + "/" + t).once('value', function(snapshot) {
             console.log("/tweets/" + goal + "/" + t);
             console.log(snapshot.val());
             var oldlikenumber = snapshot.val().likes;
             console.log(oldlikenumber);
             var newlikes = oldlikenumber + 1;
                  var tweetid = firebase.database().ref('tweets/' + goal + "/" + t).update({likes: newlikes});
                      console.log(newlikes);
              document.getElementById(t + "likes").innerHTML = newlikes;
                  });
  
  
          /* console.log('liked tweetnumber' + tweetnumber);
          alert('liked tweetnumber' + tweetnumber);
          document.getElementById('tweetnumber' + tweetnumber).innerHTML = "Likes: " + 1;*/
      }
  
      //function follow {
  
      //}
  
      function signin() {
          console.log("Signing in");
          var provider = new firebase.auth.GoogleAuthProvider();
          firebase.auth().signInWithRedirect(provider).then(function(result) { 
              window.location.replace("fbtest.html");
          });
      }
  
      function signout() {
          console.log("Signing out");
          firebase.auth().signOut().then(function() {
          });
      }
  
  
  
  &lt;/script&gt;
  
  &lt;body&gt;
      &lt;button onclick="signin()"&gt;Sign in&lt;/button&gt;
      &lt;button onclick="signout()"&gt;Sign out&lt;/button&gt;
      &lt;br&gt;
      &lt;p&gt;Step 1: delete your existing Firebase Realtime database&lt;/p&gt;
      &lt;a href="fbtest.json" target="_target"&gt;Step 2: replace JSON Firebase rules for database&lt;/a&gt;&lt;br&gt;
  
      &lt;form&gt;
          Tweet:&lt;br&gt;
          &lt;textarea id="twit" type="text" name="thetweet" cols="100" rows="4"&gt;&lt;/textarea&gt;
      &lt;/form&gt; 
      &lt;button type="button" onclick="tweet()"&gt;Submit&lt;/button&gt;
  
      &lt;br&gt;&lt;input id="inputFileToLoad" type="file" onchange="encodeImageFileAsURL();" /&gt;
      &lt;div id="imgTest" style="display:none;"&gt;&lt;/div&gt;
  
  &lt;div id="mytweets"&gt;&lt;/div&gt;
  &lt;div id="mydata"&gt;&lt;/div&gt;
  &lt;div id="myphoto"&gt;&lt;/div&gt;
  
  
  
  
  &lt;/body&gt;
  </code></pre>
  
  <p></p>
  
  <p>The problem is in the like function: The first part with var y and all that would be unnecessary if I could find a way to get the userId of the person who tweeted the tweet which the argument t denotes.</p>
  
  <p>If I can get the userId of that person (var whatever = userId that I need) then I can write:</p>
  
  <p>firebase.database().ref('/tweets/' + whatever + "/" + t).once('value', function(snapshot) {</p>
  
  <p>//same stuff</p>
  
  <p>var tweetid = firebase.database().ref('tweets/' + whatever + "/" + t).update({likes: newlikes});</p>