Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to optimize Firestore query?

I have a collection that has two subcollections and I’m fetching it like this

for (let doc of data.docs) {
  const finalPurchase = {
    ...(doc.data() as Purchase),
    classification: [],
    history: [],
  };
  finalPurchase.classification = await getClassificationDocs(cnpj, doc.id);
  finalPurchase.manufacturers = await getManufacturersDocs(cnpj, doc.id);
  finalDocs.push(finalPurchase);
}

And the subcollection query is this

const getManufacturersDocs = async (
  cnpj: string,
  parentDocId: string
): Promise<Manufacturer[]> => {
  const manufacturersRef = collection(
    db,
    "company",
    cnpj,
    "purchases",
    parentDocId,
    "manufacturers"
  );

  const manufacturersDocs = await getDocs(manufacturersRef);

  return manufacturersDocs.docs.map((item) => {
    return { ...(item.data() as Manufacturer) };
  });
};

Although it works, it’s taking a long time to get everything. Is there any way to optimize this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can try batching requests: instead of making multiple separate requests to Firestore, you can use Promise.all() to perform the requests concurrently. This can significantly reduce the total time taken to fetch the data.

Something like this:

const promises = [];

for (let doc of data.docs) {
  const finalPurchase = {
    ...(doc.data() as Purchase),
    classification: [],
    history: [],
  };

  const classificationPromise = getClassificationDocs(cnpj, doc.id);
  const manufacturersPromise = getManufacturersDocs(cnpj, doc.id);

  promises.push(
    classificationPromise.then((classification) => {
      finalPurchase.classification = classification;
    })
  );

  promises.push(
    manufacturersPromise.then((manufacturers) => {
      finalPurchase.manufacturers = manufacturers;
    })
  );

  finalDocs.push(finalPurchase);
}

await Promise.all(promises);

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading