Search code examples
javascriptgoogle-cloud-firestoreangularfire2

Firestore orderBy and where filters not working together


If I query my users collection and filter by 2 different properties as seen below, it returns the expected data.

return this.afs
  .collection<Employee>('users', ref => {
    return ref
      .where('accountId', '==', accountId)
      .where('isEmployee', '==', true);
  })
  .valueChanges()

However, if I try to order that data by name, as seen below, it returns an empty array.

return this.afs
  .collection<Employee>('users', ref => {
    return ref
      .where('accountId', '==', accountId)
      .where('isEmployee', '==', true)
      .orderBy('name');
  })
  .valueChanges()

I figured I must need to manage the way indexing is being handled or something, but did some research and my understanding is that if that were the case, I would get an error message in the console with a link to setup the composite indexing that I need. I don't get any errors though, just an empty array. What am I doing wrong? Is it possible to order a collection of data that is filtered by 2 properties? I believe I am using Firebase version 6.5, but am willing to update if that will solve my problem.


Solution

  • I would get an error message in the console with a link to setup the composite indexing that I need.

    Yes, that's correct. When you are using a query like yours, a warning message should be displayed in the console.

    I don't get any errors though, just an empty array.

    In this case, you should create that index manually in the Firebase console.

    Is it possible to order a collection of data that is filtered by 2 properties?

    Sure it is. Just create the required index and then you should be able to execute the query.