Home > Blockchain >  Filter firestore request by separate steps
Filter firestore request by separate steps

Time:04-18

I am making a filter so that a user can search for exactly a few parameters, without having to put them all in the form. For example you could search for games of type X but of all genres (Leave the form empty and it is an empty array).

I had tried doing the whole query at the same time but since there are empty arrays an exception is thrown. Consequently, I have thought of going step by step checking the filter parameters and discarding the empty ones, but I don't know how to save each step in the reference.

Technologies:

  1. Ionic
  2. Angular
  3. Firebase - Firestore

Service Code:

getFilteredResultsGames(filter: Filter) {
return this.firestore.collection<Game[]>(environment.db_tables.games,
  (ref) => {

    if (filter.types.length > 0){
      ref.where('id_type', 'in', filter.types)
    }
    if (filter.genders.length > 0) {
      ref.where('ids_genders', 'array-contains-any', filter.genders)
    }

    return ref
  }).valueChanges({ idField: 'id' });

}

Model Code:

export interface Filter {
  genders: string[];
  types: string[];
}

CodePudding user response:

Firestore queries objects are immutable. Calling where on a ref or query, doesn't modify the existing object, but rather returns a new query with the additional condition.

So to return the new query, you'd do something like:

getFilteredResultsGames(filter: Filter) {
return this.firestore.collection<Game[]>(environment.db_tables.games,
  (ref) => {
    if (filter.types.length > 0){
      ref = ref.where('id_type', 'in', filter.types)
    }
    if (filter.genders.length > 0) {
      ref = ref.where('ids_genders', 'array-contains-any', filter.genders)
    }

    return ref
  }).valueChanges({ idField: 'id' });
  • Related