2
votes

I've get a firestore collection, one of his values is an array of documents id. I need to retrieve all items of collection and also all documents stored in array ids. this is the struct of my collection enter image description here

my code:

export const getFeaturedMixes = functions.https.onRequest((request, response) => {
    let result:any[] = []
    featuredMixes.get().then(mixesSnap => {

        mixesSnap.forEach(doc => {
            let docId = doc.id
            let ids = doc.data().tracks

            let resultTracks:any[] = []
            ids.forEach(id => {
                let t = tracksCollection.doc(id.track_id).get()
                resultTracks.push({'id' : id.track_id, 'data': t})
            })
            result.push({'id':docId, 'tracks': resultTracks})
        })
        return result
    })
    .then(results => {
        response.status(200).send(results)
    }).catch(function(error) {
        response.status(400).send(error)
    })
});

and I get this response:

{
        "id": "Xm4TJAnKcXJAuaZr",
        "tracks": [
            {
                "id": "FG3xXfldeJBbl8PY6",
                "data": {
                    "domain": {
                        "domain": null,
                        "_events": {},
                        "_eventsCount": 1,
                        "members": []
                    }
                }
            },
            {
                "id": "ONRfLIh89amSdcLt",
                "data": {
                    "domain": {
                        "domain": null,
                        "_events": {},
                        "_eventsCount": 1,
                        "members": []
                    }
                }
            }
    ]
}

response doesn't contains document data

2

2 Answers

2
votes

The get() method is asynchronous and returns a Promise. Therefore you cannot do something like:

 ids.forEach(id => {
      let t = tracksCollection.doc(id.track_id).get()
      resultTracks.push({'id' : id.track_id, 'data': t})
 })

You need to wait that the Promise returned by the get() method resolves, in order to be able to use t (which is a DocumentSnapshot).

For that, since you want to fetch several documents in parallel, you need to use Promise.all().

The following should do the trick. Note that it is not tested and that there is still an easy part of the code to be completed by you, see the comments at the end. If you encounter some problem when finalizing it, add your new code to your question.

export const getFeaturedMixes = functions.https.onRequest((request, response) => {
    let result: any[] = []

    const docIds = [];

    featuredMixes.get()
        .then(mixesSnap => {


            mixesSnap.forEach(doc => {
                let docId = doc.id
                let ids = doc.data().tracks

                const promises = []

                ids.forEach(id => {
                    docIds.push(docId);
                    promises.push(tracksCollection.doc(id.track_id).get())
                })

            })

            return Promise.all(promises)
        })
        .then(documentSnapshotArray => {

            // Here documentSnapshotArray is an array of DocumentSnapshot corresponding to
            // the data of all the documents with track_ids

            // In addition, docIds is an array of all the ids of the FeaturedMixes document

            // IMPORTANT: These two arrays have the same length and are ordered the same way

            //I let you write the code to generate the object you want to send back to the client: loop over those two arrays in parallel and build your object


            let resultTracks: any[] = []

            documentSnapshotArray.forEach((doc, idx) => {
                // .....
                // Use the idx index to read the two Arrays in parallel

            })

            response.status(200).send(results)

        })
        .catch(function (error) {
            response.status(400).send(error)
        })
});
0
votes

thanks Renaud Tarnec!! it has been really hopefull your answer, function is already working, however I'd like rather to return Promise.all(primises) some object which hold the mix with his tracks, as now it's difficult to build the new object in then function, this is my final function

    const mixIDs: any[] = [];
    const mixes:any[] =[]

    featuredMixes.get()
        .then(mixesSnap => {
            const promises:any[] = []

            mixesSnap.forEach(doc => {
                let mixId = doc.id
                let mix = createMix(doc)
                mixes.push(mix)

                doc.data().tracks.forEach(track => {
                    let promise = tracksCollection.doc(track.track_id).get()
                    promises.push(promise)
                    mixIDs.push(mixId)
                })
            })
            return Promise.all(promises)
        })
        .then(tracksSnapshot => {

            let buildedTracks = tracksSnapshot.map((doc, idx) => {
                let mId = mixIDs[idx]
                return createTrack(doc, mId)
            })

            let result = mixes.map(mix => {
                let filterTracks = buildedTracks.filter(x => x.mix_id === mix.doc_id)
                return Object.assign(mix, {'tracks': filterTracks})
            })
            response.status(200).send(result)
        })
        .catch(function (error) {
            response.status(400).send(error)
        })
})