0

I am querying Firestore in Angular 8, using AngularFire. When I query a string (e.g. module_version in code below) it works, but trying to query a boolean field in Firestore doesn't work properly with my code below. I can only get all objects with active==true, but not false. When I hover the boolean variable active inside the query (in VSCode) it says "var active: true", instead of "var active: boolean" as I would have expected. I am guessing this is the problem, as I can query true, but not false. Hovering the string variable module_version gives "var module_version: string". (I have read answers to questions about true/false in Javascript, but didn't get any the wiser from this.)

Why does my variable seem to automatically get set to true and what can I do about it?

constructor(afs: AngularFirestore) {
 this.activeFilter$ = new BehaviorSubject(null);
 this.module_versionFilter$ = new BehaviorSubject(null);
  this.modules$ = combineLatest(
    this.activeFilter$,
    this.module_versionFilter$
  ).pipe(
    switchMap(([active, module_version]) => 
    afs.collection<Module>('Modules', ref => {
      let query : firebase.firestore.CollectionReference | firebase.firestore.Query = ref;
      if (active) { query = query.where('active', '==', active) };
      if (module_version) { query = query.where('module_version', '==', module_version) };
      return query;
    }).valueChanges()
    )
  );
}
Ingrid
  • 516
  • 6
  • 18
  • 1
    Am I missing something? Won't the `active` where clause only be added to the query if `active` is `true`? (because it is inside the `if (active)` block?) – robsiemb Nov 24 '19 at 20:56
  • No, you are of course right! Thanks! I was thinking it would be added if the `active` variable exists, similarly to `module_version`. But I guess I would have to do `if (active != null)` instead. – Ingrid Nov 26 '19 at 08:39
  • Possible duplicate of [How to check for an undefined or null variable in JavaScript?](https://stackoverflow.com/questions/2559318/how-to-check-for-an-undefined-or-null-variable-in-javascript) – robsiemb Nov 26 '19 at 14:02

1 Answers1

2

Thanks for the clarification in the comment thread. As discussed, your problem is that:

if (active)

Will only be true if active itself is true. So the query is only added when active is true.

You want something more like:

if (typeof(active) !== 'undefined' && active !== null)
robsiemb
  • 6,157
  • 7
  • 32
  • 46