0

I need to loop through the documents in a collection, elaborate the documents data, loop throught every document in a collection inside the document cited above and elaborate additional data. This is my structure:

jh (collection)
    x (document)
        data (map)
        provinces (collection)
            x-1 (document)
                data (map)
            x-2 (document)
                data (map)
    y (document)
        data (map)
        provinces (collection)
            y-1 (document)
                data (map)
            y-2 (document)
                data (map)

This is the snippet used to loop through all the documents and nested collections of the documents:

var worldData = {}; //TODO fill all the info

// get all the documents inside jh collection
db.collection('jh').get()
.then(collSnap => {
    // loop all country documents
    collSnap.forEach(countrySnap => {
        var countryData = countrySnap.data();
        //
        // TODO elaborate country data => worldData
        //
        // get all documents inside provinces of the country document
        db.collection("jh").doc(countrySnap.id).collection("provinces").get()
        .then(provColl => {
            // loop all province documents
            provColl.forEach(provSnap => {
                var provData = provSnap.data();
                // TODO elaborate country data => worldData
            })
        });
    });
})
//
// FIXME wait for every loop and send the informations
console.log(worldData);

How do I wait for all loops to end? I need to send the retrieved data, that I will store in worldData variable, via HTTP.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Antonio
  • 1,065
  • 3
  • 14
  • 27
  • 1
    On Stack Overflow, please limit yourself to a single question per post (else it might get closed as "needs more focus"). – Doug Stevenson Mar 25 '20 at 17:44
  • @DougStevenson done, thanks. – Antonio Mar 25 '20 at 17:48
  • You will need to collect promises into an array and use `Promise.all()` to create a new promise that resolves after every other promise resolves. This is a standard JavaScript practice not unique to Firestore. – Doug Stevenson Mar 25 '20 at 17:50

0 Answers0