简体   繁体   中英

How to access parent of child node in Firebase Realtime Database?

My Firebase Database Image 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.

This is the code for my data:

<script src="https://www.gstatic.com/firebasejs/5.7.3/firebase.js"></script>
<script src="https://apis.google.com/js/platform.js" async defer></script>

<style>
    tr:hover {background-color: #f5f5f5;}
    th, td {
        border-bottom: 1px solid #ddd;
    }

</style>
<script>

    // Initialize Firebase

var config = { apiKey: "AIzaSyA85okZdA9v_XAa9BgJJ2EOdUEbL09k0uY", authDomain: "fir-test-bcb6d.firebaseapp.com", databaseURL: " https://fir-test-bcb6d.firebaseio.com ", projectId: "fir-test-bcb6d", storageBucket: "fir-test-bcb6d.appspot.com", messagingSenderId: "976121809263" }; firebase.initializeApp(config);

    // 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 = "<img src='" + imageUrl + "'/>";

            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 > 0) {
            var fileToLoad = filesSelected[0];
            var fileReader = new FileReader();
            fileReader.onload = function(fileLoadedEvent) {
                var srcData = fileLoadedEvent.target.result; // <--- 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 = "<ul>";
        var mytab = "<table id='tweettable'>";
        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 + "<tr>";
                var date = new Date(data[u][t].time);
                var time = date.toString();                    
                if (data[u][t].img != "") {
                    mytab = mytab + "<td><img src='" + users[u].profile_picture + "' width='50px'></td>";
                    mytab = mytab + "<td>" + users[u].email + "</td>";
                    mytab = mytab + "<td>" + data[u][t].tweet + "</td>";
                    mytab = mytab + "<td>" + time + "<br><img src='" + data[u][t].img + "' width='300px'></td>";
                    mytab = mytab + "<td><p>Like this tweet</p>" + "<button id=" + t + " onclick=" + "like(this.id)" + ">Like</button>" + "<p>Likes: </p>" + "<p id='" + t + "likes'" + "'>" + data[u][t].likes + "</p>" + "</td>";

                } else {
                    mytab = mytab + "<td><img src='" + users[u].profile_picture + "' width='50px'></td>";
                    mytab = mytab + "<td>" + users[u].email + "</td>";
                    mytab = mytab + "<td>" + data[u][t].tweet + "</td>";
                    mytab = mytab + "<td>" + time + "</td>";
                    mytab = mytab + "<td><p>Like this tweet</p>" + "<button id=" + t + " onclick=" + "like(this.id)" + ">Like</button>" + "<p>Likes: </p>" + "<p id='" + t + "likes'" + "'>" + data[u][t].likes + "</p>" + "</td>";
                } 
                mytab = mytab + "</tr>";
            }   
        }
        //mylist = mylist + "</ul>";
        mytab = mytab + "</table>"
        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 < 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() {
        });
    }



</script>

<body>
    <button onclick="signin()">Sign in</button>
    <button onclick="signout()">Sign out</button>
    <br>
    <p>Step 1: delete your existing Firebase Realtime database</p>
    <a href="fbtest.json" target="_target">Step 2: replace JSON Firebase rules for database</a><br>

    <form>
        Tweet:<br>
        <textarea id="twit" type="text" name="thetweet" cols="100" rows="4"></textarea>
    </form> 
    <button type="button" onclick="tweet()">Submit</button>

    <br><input id="inputFileToLoad" type="file" onchange="encodeImageFileAsURL();" />
    <div id="imgTest" style="display:none;"></div>

<div id="mytweets"></div>
<div id="mydata"></div>
<div id="myphoto"></div>




</body>

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.

If I can get the userId of that person (var whatever = userId that I need) then I can write:

firebase.database().ref('/tweets/' + whatever + "/" + t).once('value', function(snapshot) {

//same stuff

var tweetid = firebase.database().ref('tweets/' + whatever + "/" + t).update({likes: newlikes});

Although this question is a year old and may be an XY problem, as the comments said, I believe this might answer your specific question. The only way I know of to end up with a child reference when you don't know the immediate parent is if you've retrieved a child's child via a query, in which case you can get the parent node from the documentSnapshot with .ref.key, like so:

database().ref("/users/").orderByChild("name").startAt(someText).once('value')
          .then(querySnapshot => {

               querySnapshot.forEach(docSnapshot => {

                   console.log("parent = " + docSnapshot.ref.key);

                   // if this docSnapshot was retrieved because of child "name"'s value
                   // at https://someapp-firebaseio.com/users/uid8234/name
                   // then docSnapshot.ref.key == uid8234

               })
          })

This might happen if you store user data under uid nodes in /users/, with "name" as one of the children of each uid node, for instance. Of course, to avoid retrieving that, you could also store an extra copy of the uid in another key alongside "name" and reference that instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM