Question:
How to optimize getting multiple documents 'one by one' in Firestore?

Problem:

I'm using Node.js + Firestore. To provide more context, the structure of my database is as follows:

Firestore

|

|-- card (Collection)

|    |-- SCP-002 (Document)

|    |    |-- name: The "Living" Room

|    |    |-- file: http://scp-es.com/scp-002

|    |

|    |-- SCP-003 (Document)

|         |-- name: Biological Motherboard

|         |-- file: http://scp-es.com/scp-003

|

|-- obtention (Collection)

     |-- 7UHIhguG767F

     |    |-- user: /user/32138217391

     |    |-- card: /card/REG-001

     |

     |-- KkNJbVCr65TY

          |-- user: /user/08498328422

          |-- card: /card/REG-002


The fields in the 'obtention' documents are references to documents in the 'cards' collection. Therefore, if I want to access the data of a user's cards (such as the name) e.g for a console list, I do the following:


const userReference = database.collection('user').doc(interaction.user.id);


const cardsReference = database.collection('obtention').where('user', '==', userReference);

const cardsSnapshot = await cardsReference.get();


const cards = [];


for (const x of cardsSnapshot.docs) {

     const obtention = x.data();

     const cardReference = obtention.card;

     const cardDocument = await cardReference.get();


     cards.push(cardDocument);

}



// Rest of the code


The code works as expected, but the issue is that it takes a long time to fetch card records, and this delay increases with more data (7 seconds for about 10 records). My question is whether there's a way to speed up this process and reduce the time it takes to obtain the same result?


Solution:

Don't use an await for each individual cardReference.get() call, but gather all of these calls into an array and then pass that to Promise.all.

const promises = [];


for (const x of cardsSnapshot.docs) {

     const obtention = x.data();

     const cardReference = obtention.card;


     promises.push(cardReference.get());

}


const cards = await Promise.all(promises);




Suggested blogs:

>How to write specific dictionary list for each cycle of loop?

>Reading a shapefile from Azure Blob Storage and Azure Databricks

>How to replace a value by another in certain columns of a 3d Numpy array?

>How to fix "segmentation fault" issue when using PyOpenGL on Mac?

>How can I Find the Largest Prime Value in a Dictionary of ASCII Sums?

>How to adjust the size of marginal distribution plots in Plotly Express?

>Why it is showing Rout Url 404 - File or directory not found in Vuejs?

>Why VueJs console.log giving the correct value but not updating in the template?


Ritu Singh

Ritu Singh

Submit
0 Answers