Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase Web retrieve data

I have the following db structure in firebase

enter image description here

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 image description here

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

like image 575
CyberJunkie Avatar asked Aug 22 '16 15:08

CyberJunkie


People also ask

How can I get Firebase data from my website?

For reading a data from the Firebase Realtime database, Firebase has two methods on() and once() . on() method to retrieve data. This method is taking the event type as “value” and then retrieves the snapshot of the data. When we add val() method to the snapshot, we will get the JavaScript representation of the data.

How to retrieve data in Firebase database?

Firebase data is retrieved by either a one time call to GetValueAsync() or attaching to an event on a FirebaseDatabase reference. The event listener is called once for the initial state of the data and again anytime the data changes.

How do I get data from QueryDocumentSnapshot?

A QueryDocumentSnapshot contains data read from a document in your Cloud Firestore database as part of a query. The document is guaranteed to exist and its data can be extracted using the getData() or the various get() methods in DocumentSnapshot (such as get(String) ).


1 Answers

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.

like image 103
pr0gramist Avatar answered Oct 19 '22 00:10

pr0gramist