7

[**enter image description here**enter image description here

I am trying to query the post-collection with the user settings but the settings is an array of more than 10 elements and nothing is returned. I know the documents did mention the limit of 10 elements, does anyone know a workaround?

firebaseApp.collection('posts')
            .where("newTag", "in", mySettings)
            .get()
let array = [];
        posts.forEach((post) => {
            array.push(post.data());
        });

dispatch({ type: ActionTypes.GET_POSTS, payload: array });
marc_s
  • 704,970
  • 168
  • 1,303
  • 1,425
Cho Cho
  • 119
  • 3
  • 11

3 Answers3

3

A simple function to chunk the array could solve your problem:

const chunkArray = (list: any[], chunk: number): any[][] => {
    const result = [];

    for (let i = 0; i < list.length; i += chunk) {
        result.push(list.slice(i, i + chunk));
    }

    return result;
};

export { chunkArray };

Then a for await hack to get the snaps would work as well:

  const snaps_collection: FirebaseFirestore.QuerySnapshot[] = [];

  for await (const snap of chunks.map(
    async (chunk) =>
      await database
        .collection("collection_name")
        .where("id", "in", chunk)
        .get()
  )) {
    snaps_collection.push(snap);
  }
Andre Sampaio
  • 334
  • 3
  • 6
2

The workaround is to perform a query for each item in mySettings individually, and merge the results on the client. Or, split mySettings into another collection of arrays that each have 10 or less items, query for each one of those individually, and merge the results on the client.

Doug Stevenson
  • 268,359
  • 30
  • 341
  • 380
  • 2
    How about a Twitter-like application that needs to show tweets from all followed users in the feed? A user might follow several hundred other users, in which case merging the results on the client would cause tons of additional reads. – Max Oct 27 '20 at 11:17
  • 2
    I would say this works unless you are trying to do pagination using `limit` – krummens Nov 09 '20 at 03:58
1

Do a wherein using a chunk of the array of mysettings, each chunk could have a maximum size of 10, then join the results into a single array

pedrommuller
  • 15,360
  • 9
  • 71
  • 124