Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query arrays values with Firebase

Is there any way to on Firebae to filter data in an array?

I have this model on my Firebase:

-KABIGeWnBMUKjLTcvp8  
  deviceToken:"7DE60240CB4B712F05A009F32358610C1327917E7E68409..."
  favorites
    0:"Masha"
    1:"moksha"
  name:"juan"

And the problem is that I can't find any method to get all "users" that contain a certain value on the "favorites" array field.

like image 966
juanObrach Avatar asked Jan 06 '23 16:01

juanObrach


2 Answers

Nope, that's not an option See firebase equivalent to sql where in ().

Instead: invert your data structure to make this query possible:

items_by_favorites
  "Masha"
    "-KABIGeWnBMUKjLTcvp8"
  "moksha"
    "-KABIGeWnBMUKjLTcvp8"

Now you can look up the item keys for Masha with a simple read: ref.child('items_by_favorites/Masha') and then load each item:

ref.child('items_by_favorites/Masha').on('value', function(snapshot) {
  snapshot.forEach(function(childSnapshot) {
    var key = childSnapshot.key();
    ref.child('items').child(key).once('value', function(itemSnapshot) {
      console.log(itemSnapshot.val());
    });
  });
})
like image 114
Frank van Puffelen Avatar answered Jan 16 '23 08:01

Frank van Puffelen


First of all your question is answered deep in the guide for retrieving data, which is where I got this answer. It's under complex queries, then range queries, should you want more info.

var ref = new Firebase("https://dinosaur-facts.firebaseio.com/dinosaurs");
ref.orderByChild("height").equalTo(25).on("child_added", function(snapshot) {
  console.log(snapshot.key());
});

The basic idea is that you need to first order the reference by a common child value, and then call .equalTo() to end up with a query that yields what you want.

Also you can call order by child like

ref.orderByChild("height/sublevel")

To drill deeper in the tree.

like image 26
wolf123450 Avatar answered Jan 16 '23 09:01

wolf123450