How to create a logical OR query in Cloud Firestore with the JavaScript SDK?
With Cloud Firestore, we can combine multiple where()
methods to create logical AND
queries. These queries are called compound queries in the documentation.
However, as indicated in the documentation (Section “Query Limitations”):
Cloud Firestore does not support the following types of queries:
- …
- LogicalOR
queries. In this case, you should create a separate query for eachOR
condition and merge the query results in your app.
- …
The aim of this short article is to show how to implement, with the JavaScript SDK, the solution indicated above to “simulate” a Logical OR Query.
Firstly, let’s create a set of example data. Like the example in the documentation, we are going to create some Firestore records for a set of cities.
Let’s see now an example of a Logical OR Query. Let’s query all the cities that are a capital city OR an Italian city.
The following code will do the trick:
Let’s detail how this code works.
We first create an async function called getIsCapitalOrCountryIsItaly()
which:
- Defines two promises, using the
get()
method of aQuery
. The first query will return all the Capital cities, while the second will return the Italian ones. - Uses
Promise.All()
which “returns a singlePromise
that resolves when all of the promises passed as an iterable have resolved”¹, in order to get an array ofQuerySnapshots
. - Creates two arrays, one for each query, using the
docs
property of aQuerySnapshot
which returns “an array of all the documents in theQuerySnapshot
”. - Merges the two arrays by using the
concat()
method and returns the resulting array.
Then, the code simply calls this asynchronous function.
This works well, but, if you try it you will see that we get twice the city of Rome, since it is the capital city of Italy.
So we need to de-duplicate the arrays. One possible solution is to use the Lodash library and adapt the last two lines² of the getIsCapitalOrCountryIsItaly()
function as follows:
Let’s look at another example: We want to query all the cities with population under 500,000 or over 1,5M.
We just have to slightly adapt the previous function as follows:
That’s it! We are now able, with the JavaScript SDK, to combine two (or more) different Firestore queries to “simulate” a logical OR query.
If you have any question or suggestion, please leave a comment below.
#BetterTogether
[1] See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
[2] Strictly speaking, we don’t need to adapt the first line of those two last lines, since the way we construct the citiesArray
array is totally valid. But since we start using Lodash, let’s just take advantage of it and also adapt this line!