0

I have a list of instances in my Firebase database, and I want to filter the list if and only if the the user chooses to filter the query. If the user doesn't choose to filter the query I just want to output all instances

What I am trying to do.

var ref = new Firebase("myfirebaseurl");

if(condition){
  var query = ref.orderByChild("somechild").equalTo("conditionchosen");
} else {
  var query = ref.orderByChild("somechild").equalTo(any value);
}

Any way to do this?

Cœur
  • 37,241
  • 25
  • 195
  • 267

2 Answers2

2

Only perform queries if you are looking for a specific set of data. They have a lot more overhead than observing a node.

So if you are looking for something, do a query, if you just want all data (i.e. equalTo any value) observe the node.

if ( condition_chosen ) {
   var query = ref.orderByChild("somechild").equalTo(condition_chosen)
      .observeSingleEventOfType(.Value.... {
       })
} else {
   ref.observeSingleEventOfType(.Value... {
   } )
}
Jay
  • 34,438
  • 18
  • 52
  • 81
  • Oh okay, another question if I may. Is it possible to check if the child is partly equal to. – Christoffer Hansen May 27 '16 at 19:48
  • Unfortunately, Firebase does not do partial string searches - it's all or none. However, there are ways around that! See my answer to [This Question](http://stackoverflow.com/questions/36870425/swift-how-can-i-use-shouldchangetextinrange-with-firebase-for-real-time-sear/36872475#36872475) – Jay May 27 '16 at 20:03
  • It does support `startsWith` like operations, but not `CONTAINS`. So in SQL parlance, `bla%` but not `%bla%`. – Frank van Puffelen May 28 '16 at 01:17
  • I can't seem to find any docs on the startsWith? The closest i get is this https://github.com/davideast/Querybase. – Christoffer Hansen May 28 '16 at 09:11
  • 1
    @FrankvanPuffelen I think we are speaking of queryStartingAtValue:. So if you have a series of names. Frank, Jim, Leroy and you want to find all names starting with 'J' add queryStartingAtValue("J") – Jay May 28 '16 at 12:40
0

Firebase Version 8.0

this.firestore.collection('/collectionName', ref => {
   let query: firebase.firestore.CollectionReference | firebase.firestore.Query = ref;
      if (filter1) { query = query.where('Collection_filter1', '==', filter1) };
      if (filter2) { query = query.where('Collection_filter2', '==', filter2) }; 
}

Firebase Version 9.0

let q = query(collection(this.firestore, "collectionName"));
if (filter1) {
    q = query(q, where("filter1", "==", filter1));
}
if (filter2) {
    q = query(q, where("filter2", "==", filter2));
}
alvaroIdu
  • 443
  • 4
  • 7