How to fix Uncaught Error in onSnapshot: FirebaseError: The query requires an index. on dynamic sorting?

Viewed 1549

I have a query where I am querying in a desc order using as follows

  const { id } = userDetails;
  const initialQuery = await firestore().collection('class')
    .orderBy('createdAt', 'desc')
    .where(`access.readAccess.${id}`, '==', true)
    .limit(5);
  initialQuery.onSnapshot((documentSnapshots) => {
    const { docs } = documentSnapshots;
    const lastVisible = docs.length > 0 ? docs[docs.length - 1] : '';
    console.log(docs);
  })
const getMore = async(store, userDetails) => {
  const { id } = userDetails;
  const { lastVisible } = lastState;
  const initialQuery = await firestore().collection('class')
    .orderBy('createdAt', 'desc')
    .where(`access.readAccess.${id}`, '==', true).startAfter(lastVisible)
    .limit(5);
  const documentSnapshots = await initialQuery.get();
  const { docs } = documentSnapshots;
}

When I do this I get an error of The query requires an index which seems fair and also helpful url to create the indexing. As I create the indexing it creates indexing of

class
access.readAccess.`1571158795762` Ascending createdAt Descending
Collection
Enabled

Now in this 1571158795762 will keep changing based on the user logged in. So, of course, it started complaining about the other user. Also, onSnapshot doest get called with desc order. Any suggestion, please?

1 Answers

A Cloud Firestore index needs to know about all of the specific fields participating in the query. This is how it can optimize the query. If one of your query fields is dynamically named, such as your access.readAccess.${id}, then this sort of query is not well suited for Firestore.

The only way around this is to restructure you data in such a way that's compatible with Firestore's requirements for the index. Since we're not given a good view into the data you're trying to store, it's not really possible to give a working suggestion. But I will say that moving the IDs into a list and checking that list for the existence of the ID in the query might be helpful.

Related