0

In the Firestore documentation, it states clearly the limitations of support for query filters with logical OR.

For example:

const userPostsQuery = query(postsRef, where("author", "==", uid);

const publicPostsQuery = query(postsRef, where("public", "==", true);

If as in the above example, we need to get a list of both, user posts and public posts all sorted together by date, ie: Both queries need to be OR-ed together, such a feature is not available in Firestore and we will have to run both queries separately, and then merge and sort the results on the client-side.

I'm fine with such a sad workaround. but what if the total number of posts can be huge? thus we need to implement a pagination system where each page shows 50 posts max. How can this be done with such a sad workaround?

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
Menas
  • 1,059
  • 1
  • 9
  • 19

1 Answers1

3

Firestore has very limited operators and aggregation options. However, it has limited OR support with an Array type.

A solution that could simplify your use case is to introduce a new field of type array in your post document. Let's say this field is named a. When you create your document, a is equal to [authorId, 'public'] if the post is public, [authorId] otherwise.

Then, you can query your need using the array-contains-any operator:

const q = query(postRef, where('a', 'array-contains-any', [authorId, 'public']));

You can easily add pagination with limit, orderBy, startAt, and startAfter functions.

Laurent
  • 14,122
  • 13
  • 57
  • 89
  • This approach is definitely valid and seems to be the best approach available, and I've thought of it. but unfortunately, the example I provided is just a simplified hypothetical example. I can't use this in the real use case that I have. – Menas Dec 14 '22 at 09:55