Home > other >  Firestore in query problems
Firestore in query problems

Time:12-25

I have an array field in Firestore that looks like that ['west_coast', 'east_coast'] I want to get results if west_coast and east_coast are found in the same array from dynamic data

It works when I do it as in the example on the Firestore site.

const exactlyOneCoast = await citiesRef.where('region', 'in',[['west_coast', 'east_coast']]).get();

but since the data comes dynamically, if the place of the data in the array is different, it does not give any results.

const exactlyOneCoast = await citiesRef.where('region', 'in',[['east_coast', 'west_coast']]).get();

I want it to find it even if they change places. Is there a way to do this?

CodePudding user response:

The query you are doing is looking for an exact array match [docs]

You can use an array value as a comparison value for in, but unlike array-contains-any, the clause matches for an exact match of array length, order, and values.

If you drop one set of brackets, it will return if region is either west_coast or east_coast

citiesRef.where('region', 'in',['east_coast', 'west_coast'])

The in, array_contains, and array_contains_any operators are logical OR searches, so if you want to return documents where an array (in your document) contains both elements, then you need to do a compound query.

citiesRef.where('region', 'array_contains', 'east_coast').where('region', 'array_contains', 'west_coast')

CodePudding user response:

If you have an array field called "region" that holds two values "east_coast" and "west_coast", then there is no way you can use the following query:

const exactlyOneCoast = await citiesRef.where('region', 'in',[['west_coast', 'east_coast']]).get();

Nor:

const exactlyOneCoast = await citiesRef.where('region', 'in',[['east_coast', 'west_coast']]).get();

Why? Because the in operator works only against a field of type String and not against a field of type array. So if you have a field of type String, the in query returns documents where the given field matches any of the comparison values.

If you need to check if a particular value exists in an array, then you should use the array_contains operator. Since you cannot chain multiple such calls, then you should perform multiple separate database calls.

  • Related