Search code examples
javascriptangularfirebasegoogle-cloud-firestoreangularfire

Cloud Firestore query and limit doesn't query all data


I have a list with tags that I want to search in and retrieve data that matches the search.

I can retrieve all data correct with this query

  searchTags(search: string): AngularFirestoreCollection<Tag> {    
    return this.afs.collection(this.dbPathTags, ref => ref.where('tag', "<=", search))
  }

But the problem is that i want to limit the results to 5, since I'm planning to show them in a dropdown/autocomplete (like tags in SO)

After adding the limit, the query is just searching for the top 5 items from db and ONLY returns any of them if they matches. Wanted result is query filter ALL items then returns 5 items

  searchTags(search: string): AngularFirestoreCollection<Tag> {    
    return this.afs.collection(this.dbPathTags, ref => ref.where('tag', "<=", search).limit(5))
  }

When searching for "a" I get this result

enter image description here

But when searching "m" or "math" I don't get anything, note that "math" is also in the db and is displayed when the limit is off

enter image description here

Limit off

enter image description here


Solution

  • Have considered using startAt with the Limit rather than the where. Firebase Pagination docs https://firebase.google.com/docs/firestore/query-data/query-cursors.

    edit: .orderBy('field', 'order') when order is not present ascending order is default

    searchTags(search: string): AngularFirestoreCollection<Tag> {    
        return this.afs.collection(this.dbPathTags, ref => ref.orderby('field', 'order').startAt(search).limit(5))
      }
    

    Maybe something like that?