Retrieve a collection of Firestore documents based on an array of unique identifiers

I have a Firestore collection where one of the values is an array of document IDs. My goal is to retrieve all items in the collection as well as all documents stored within the array of IDs. Here is the structure of my collection:

This is 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)
    })
});

However, the response I receive is missing the actual document data:

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

The response does not contain the actual document data.

Answer №1

The method called get() operates asynchronously and returns a Promise. This means that you cannot immediately do something like:

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

You must allow the Promise returned by get() to resolve before being able to use t (which is of type DocumentSnapshot).

To handle fetching multiple documents concurrently, it's necessary to utilize Promise.all().

The following code snippet should accomplish this task. Please note that it has not been tested, and there are still sections in the code that require completion as indicated in the comments at the end. If you face any issues while finalizing it, feel free to update your question with the new code.

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

Answer №2

Appreciate the assistance, Renaud Tarnec! Your response has been incredibly valuable. The function is currently operational, but I am interested in returning a Promise.all(promises) object that contains the mix along with its tracks. Building the new object within the "then" function has proven to be challenging. Here is my finalized 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 builtTracks = tracksSnapshot.map((doc, idx) => {
                let mId = mixIDs[idx]
                return createTrack(doc, mId)
            })

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the reason for the lack of compatibility between the TypeScript compilerOptions settings 'noEmitOnError: true' and 'isolatedModules: false'?

Whenever I try to execute TypeScript with isolatedModules set as true and then false, I keep encountering this error message: tsconfig.json(5,9): error TS5053: Option 'noEmitOnError' cannot be specified with option 'isolatedModules'. ...

The code below is not working as it should be to redirect to the home page after logging in using Angular. Follow these steps to troubleshoot and properly

When looking at this snippet of code: this.router.navigate(['/login'],{queryParams:{returnUrl:state.url}}); An error is displayed stating that "Property 'url' does not exist on type '(name: string, styles: AnimationStyleMetadata". ...

What sets apart the commands npm install --force and npm install --legacy-peer-deps from each other?

I'm encountering an issue while trying to set up node_modules for a project using npm install. Unfortunately, the process is failing. Error Log: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolv ...

Consistentize Column Titles in Uploaded Excel Spreadsheet

I have a friend who takes customer orders, and these customers are required to submit an excel sheet with specific fields such as item, description, brand, quantity, etc. However, the challenge arises when these sheets do not consistently use the same colu ...

Eliminating the "undefined" error in TypeScript within a React application

Having recently dived into TypeScript configuration, I encountered an issue when coding and tried to resolve it by encapsulating the code block in an if statement checking for usersData to eliminate the "Object is possibly undefined" errors. However, upon ...

Generating step definitions files automatically in cucumber javascript - How is it done?

Is there a way to automatically create step definition files from feature files? I came across a solution for .Net - the plugin called specflow for Visual Studio (check out the "Generating Step Definitions" section here). Is there something similar avail ...

In TypeScript, the 'as const' syntax results in a syntax error due to the missing semicolon

I incorporated the following code into my react project: export const animation = { WAVES: "waves", PULSE: "pulse", } as const; export type Animation = typeof animation[keyof typeof animation]; Upon running the project, I encounte ...

Position components in Angular 2 based on an array's values

Hello all, I am a beginner in terms of Angular 2 and currently facing some obstacles. My goal is to create a board for a board game called Reversi, which has a similar layout to chess but with mono-color pieces. In order to store the necessary information, ...

dynamic padding style based on number of elements in array

Is there a way to set a padding-top of 10px only if the length of model.leaseTransactionDto.wagLeaseLandlordDto is greater than 1? Can someone provide the correct syntax for conditionally setting padding based on the length? Thank you. #sample code <d ...

Exploring the depths of complex objects with the inclusion of optional parameters

I've been working on a custom object mapping function, but I've encountered an issue. I'm trying to preserve optional parameters as well. export declare type DeepMap<Values, T> = { [K in keyof Values]: Values[K] extends an ...

Using an external module in a Vue SFC: a beginner's guide

Recently delving into Vue, I'm working on constructing an app that incorporates Typescript and the vue-property-decorator. Venturing into using external modules within a Single File Component (SFC), my aim is to design a calendar component utilizing t ...

My reselect function seems to be malfunctioning - I'm not receiving any output. Can anyone help me

I'm looking to implement reselect in my code to retrieve the shopping cart based on product ids. Here's my reselect.ts file: import { createSelector } from "reselect"; import { RootState } from "../store"; export const shopp ...

Tips on displaying substitute text in Angular when an Iframe fails to load the content located at the src

Currently, I am working on an Angular 12 application and have a requirement to fetch content from an external site and display it within a modal popup. To achieve this, I am using the <iframe src="url"> tag to retrieve the content from a se ...

Troubleshooting: Why is the Array in Object not populated with values when passed during Angular App instantiation?

While working on my Angular application, I encountered an issue with deserializing data from an Observable into a custom object array. Despite successfully mapping most fields, one particular field named "listOffices" always appears as an empty array ([]). ...

Differences between RxJs Observable<string> and Observable<string[]>

I'm struggling to grasp the concept of RxJS Observables, even though I have utilized the observable pattern in various scenarios in my life. Below is a snippet of code that showcases my confusion: const observable: Observable<Response> = cr ...

Error message indicating that the function is not defined within a custom class method

I successfully transformed an array of type A into an object with instances of the Person class. However, I'm facing an issue where I can't invoke methods of the Person class using the transformed array. Despite all console.log checks showing tha ...

Passing a custom data type from a parent component to a child component in React

I'm currently working on developing a unique abstract table component that utilizes the MatTable component. This abstract table will serve as a child element, and my goal is to pass a custom interface (which functions like a type) from the parent to t ...

Angular array sanitization for handling multiple URLs

I need to sanitize multiple URLs from an array containing links to video sites e.g.: videos: SafeResourceUrl = ['www.someURL1', 'www.someURL2',... ]; To achieve this, I created a constructor like so: constructor(private sanitizer ...

What is the most effective method for designing a scalable menu?

What is the most effective way to create a menu similar to the examples in the attached photos? I attempted to achieve this using the following code: const [firstParentActive, setFirstParentActive] = useState(false) // my approach was to use useState for ...

Refreshing Form after Saving in Angular 4

After clicking the Save button, I want to reset the form (addUserForm). I created a modal with a form to input user data. This form serves for both editing existing data and creating new data, with the flag 'Create' or 'Update' differen ...