Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase Firestore query an array of more than 10 elements

[**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 });
like image 812
Cho Cho Avatar asked Dec 09 '19 22:12

Cho Cho


Video Answer


2 Answers

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);
  }
like image 92
Andre Sampaio Avatar answered Sep 20 '22 20:09

Andre Sampaio


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.

like image 21
Doug Stevenson Avatar answered Sep 18 '22 20:09

Doug Stevenson