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 retrieve the data
var getClassInfo = firebase.database().ref().child('Classes'+ user.uid +
'/');
getClassInfo.on('value', gotData,errData);
function gotData(data) {
//console.log(data.val());
var Classes = data.val()
var keys = Object.keys(Classes);
console.log(keys);
for (var i =0; i < keys.length; i ++){
var k = keys[i];
var TheClass = Classes[k].TheClass;
console.log(TheClass);
}
}
function errData(err) {
console.log('Error!');
console.log(err);
}
How do I ref() the value of the push()?
var getClassInfo = firebase.database().ref().child('Classes'+ user.uid +
[push()]);
How do I retrieve all classroom name from a particular user [TheClass]?
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 name
s 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.