Rising
Rising

Reputation: 1

ReactJS Firebase multiple where clause isn't working

I'm developing an application which need's to fetch users based on prefered preferences but the sorting isn't functioning.

export const fetchUsers = (minAge, maxAge, prefer, gender) => 
  db.collection('profiles')
    .where('age', '>=', minAge)
    .where('age', '<=', maxAge)
    //.where('gender', '==', prefer)
    .get()
    .then(snapshot => snapshot.docs.map(doc => ({id: doc.id, ...doc.data()})))

When I use the three where clauses it should return a user but it returns zero. When I only use age or only use gender the query returns the correct data.

Why aren't the three where clauses not returning data and it only works when I use where on age or gender?

I've tried to change the .where clause to .where({...}) but this is incorrect code. Also i've tried to filter on only minAge and gender but also returns zero data, while it should return a user.

Upvotes: 0

Views: 50

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 599956

Firestore queries always work based on one or more indexes. In the case where you have conditions on multiple fields, it often needs a so-called composite index on those fields. Firestore automatically adds indexes for the individual fields, but you will have to explicitly tell it to create composite indexes.

When you try to execute a query for which the necessary index is missing, the SDK raises an error that contain both the fact that an index is missing and a direct link to the Firestore console to create exactly the index that the query needs. All fields are prepopulated, so you just need to click the button start creating the index.

If you don't see the error message/link in your apps logging output yet, consider wrapping the query in a try/catch and logging it explicitly.

Upvotes: 1

Related Questions