1

I am trying to filter a collection by a field value and also get all entries where the field is equal to null. Since the in operator does not support null values, I can not take the simple route and query for:

where('field', 'in', ['value', null])

I am currently solving this issue by having two queries. One getting the entries where the field is null and one getting the entries where the field equals the value:

where('field', '==', 'value')
where('field', '==', null)

But this returns me more entries than necessary, and I have to sort and merge the entries client side. I would rather have a single query return me all entries, so I can do things like pagination across the combined list, rather than paginating over both list separately.

Is there any method to accomplish this?

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
Nestoro
  • 787
  • 6
  • 17

2 Answers2

2

In addition to Doug's answer, I'll say that it might be a workaround, which is instead of storing null, you can store null as a string. That being said, the following query:

where('field', 'in', ['value', 'null'])
//                               

Will return the desired results. Not ideal, but it will do the job.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • Hey Nestoto. Have you tried the solution in my answer? Does it work? – Alex Mamo Aug 07 '22 at 07:34
  • works like a charm, i am just not completely sold on the idea to convert every null value to 'null' and convert every string i get from the database that equals 'null' to null. could lead to some weird interactions in rare cases – Nestoro Aug 07 '22 at 11:09
  • Good to hear that it worked. Yep, that's just a workaround that can be used until such operations will be possible. – Alex Mamo Aug 07 '22 at 11:53
1

No, there is currently no alternative to making multiple queries for each condition. Firestore does not support logical "OR" queries, except for "in" (which does not work for this specific case, as you have seen).

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441