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?
>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);