How to filter Firebase Documents that are in a list of DocumentReferences?

Viewed 207

I'm currently building a social network app using Firebase and Flutter, and I've stumbled onto a bit of a problem. My homepage has two tabs, one that contains all posts on the app in chronological order, and the other that contains the posts of the people you follow. The DocReferences of the people the user follows is inside a list. Currently, the code looks like this:

 if (myFollows.isNotEmpty)
        for (int j = 0; j < myFollows.length; j++) {
          await FirebaseFirestore.instance
              .collection('posts')
              .orderBy('date', descending: true)
              .where('user', isEqualTo: myFollows[j])
              .get()
              .then((value) {
              //code
              });

But, as you can see, I create seperate queries for each of the followed users, so the resulted list of posts isn't in chronological order.

So, my question is, if there is a way I could query the post documents where the user variable is contained inside the list myFollows, instead of comparing it to each of its values one by one?

1 Answers

Remove the loop and use whereIn. This should work

 if (myFollows.isNotEmpty)
   
      await FirebaseFirestore.instance
          .collection('posts')
          .orderBy('date', descending: true) 
          .where('user', whereIn: myFollows) //this line changed
          .get()
          .then((value) {
          //code
          );

In your 1st execution, you may need to add a new index... just follow the web link (in error message) that will help create this required index.

May not work if following more than 10 users as this is a built-in limit in Firestore (maximum 10 comparisons).

In that case, there is no built-in solution... you need to keep your loop and append every single query separately... then sort your final list.

Related