Skip to content Skip to sidebar Skip to footer

How Can I Get The Reference Of The Push() In Firebase Database?

I want to retrieve the data from my firebase database. The one that was highlighted in the IMG 1 is the user uid and below it was the value from the push(). This is my code to re

Solution 1:

To get the value of the classroom created via the push, do as follows, where classId is the key created by the push (e.g. LMpv.....)

    firebase.database().ref('Classes/' + user.uid + '/' + classId).once('value').then(function (snapshot) {           
        console.log(snapshot.val().TheClass);
        // ....
    });

To retrieve all the classroom names for a particular user, do as follows:

var userRef = firebase.database().ref().child('Classes' + '/' + user.uid);
userRef.once('value', function(snapshot) {
  snapshot.forEach(function(childSnapshot) {
    var childData = childSnapshot.val();
    var classroomName = childData.TheClass
  });
});

By using the once() method, you read once the values from the database, see https://firebase.google.com/docs/reference/js/firebase.database.Reference#once

If you want to use the on() method (as you do in your question) and continuously listen to the user node and detect when new classrooms are added, do as follows:

var userRef = firebase.database().ref().child('Classes' + '/' + user.uid);
userRef.on('child_added', function(data) {
  console.log(data.val().TheClass);
});

See the doc here and here.

Post a Comment for "How Can I Get The Reference Of The Push() In Firebase Database?"