Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
87
rated 0 times [  93] [ 6]  / answers: 1 / hits: 20938  / 8 Years ago, mon, august 22, 2016, 12:00:00

I have the following db structure in firebase



enter



I'm trying to grab data that belongs to a specific user id (uid). The documentation has the following example:



firebase.database().ref('/users/' + userId).once('value').then(function(snapshot) {
var username = snapshot.val().username;
// ...
});


But how can I retrieve data from my example without knowing the unique key for each object?



Update:



I tried a new approach by adding the user id as the main key and each child object has it's own unique id.



enter



Now the challenge is how to get the value of title.


More From » json

 Answers
54
firebase.database().ref('/tasks/').orderByChild('uid').equalTo(userUID)


Well that is pretty straightforward. Then you can use it like this:



return firebase.database().ref('/tasks/').orderByChild('uid').equalTo(userUID).once('value').then(function(snapshot) {
var username = snapshot.val().username;
// ...
});


Of course you need to set userUID.



It is query with some filtering. More on Retrieve Data - Firebase doc



Edit: Solution for new challenge is:



var ref = firebase.database().ref('/tasks/' + userUID);
//I am doing a child based listener, but you can use .once('value')...
ref.on('child_added', function(data) {
//data.key will be like -KPmraap79lz41FpWqLI
addNewTaskView(data.key, data.val().title);
});

ref.on('child_changed', function(data) {
updateTaskView(data.key, data.val().title);
});

ref.on('child_removed', function(data) {
removeTaskView(data.key, data.val().title);
});


Note that this is just an example.


[#60960] Friday, August 19, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
efren

Total Points: 186
Total Questions: 85
Total Answers: 112

Location: Turkmenistan
Member since Sat, Apr 16, 2022
2 Years ago
;