Mapping nested array of references in Angular Firestore

I am working with a collection called A, which contains documents that reference other documents in collection B.

https://i.sstatic.net/C1HtT.png

When fetching my A documents from the service, I receive an array of objects that are not usable. However, I want to be able to view them as well.

  getAs() {
      this.aService.getAs().subscribe((data) => {
        this.aArray = data.map((e) => {
          return {
            id: e.payload.doc.id,
            ...(e.payload.doc.data() as {}),
          } as A;
        });
      //TODO some magic to get a nice array of B's inside every A
      });
   }

https://i.sstatic.net/O6suh.png

It is crucial for me to retrieve an array of A objects with arrays of B objects inside, rather than having two separate arrays for A and B.

I hope I have communicated my needs clearly. Thanks in advance

Answer №1

Explained in the documentation for Firestore found here, a document reference in Firestore points to a specific location within the database where a document is stored. This reference can be used to interact with the document by reading, writing, or monitoring changes. It's important to note that the reference itself does not contain the actual document data, requiring a separate query to fetch it.

To retrieve the document data associated with each reference in the `array_of_bs`, you will need to iterate through each reference, fetch the corresponding document using its path, and store the data in a temporary array. Then, merge this data with the results obtained from the `map()` function as demonstrated below:

async getAs() {
   this.aService.getAs().subscribe(async (data) => {
     const promises = await data.map(async (e) => {

       // temporary array to store document data for b
       let array_of_bs = [];

       // iterate over each reference in array_of_bs
       for (const path of (e.payload.doc.data() as any).array_of_bs) {
         const bObj = await this.afs.doc(path).get().toPromise();
         array_of_bs.push(bObj.data());
       }

       return {
         id: e.payload.doc.id,
         ...(e.payload.doc.data() as {}),
         array_of_bs: array_of_bs // replacing previous array_of_bs with fetched document data
       } as A;
     });

     const docValues = await Promise.all(promises);

     console.log(docValues);
   });
 }

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

A guide to accessing a property value in Angular 6 from an object using a string key

In my Angular application, I am receiving an object with multiple arrays from a REST service. I need to access the value from the incoming object based on the property name. Here is what the object looks like: data{ array1:{}, array2:{}, array3:{} } Th ...

Is it possible to utilize filter in place of forEach in Javascript?

Is there a way to refactor the function below that currently uses forEach to instead use filter? I've searched online but couldn't find a suitable solution. pendingPaymentsUtils.getPendingPayment = paymentId => { const payments = pendingPay ...

What is the most straightforward method for summing all elements in a 2D array based on their position in Ruby?

Looking for the most straightforward and efficient method to add up all the elements in a 2D array based on their positions using Ruby. Take this example: 2darray = [[1,2,3],[1,2,3]] result = [2,4,6] This is the code I currently have: def sum_elements_b ...

typescript decorator implemented on a class that is nested within another class

Is it possible to decorate a nested property within a class? Let's explore with an example: function log(name: string = 'DecoratedProp') { return function logHandler(target: any, field: any) { // get the key ...

Using Angular 2 to implement a custom dropdown feature with the ngModel directive

I've created a unique custom component that displays employment types in a dropdown menu and allows the user to select one. Here is the code for the component: import { Component, OnInit } from "@angular/core"; import { EmploymentType } from '. ...

Download and store the response body using FileSaver and blob technology

I'm encountering an issue where I am trying to download and save a file from an API. The original filename is text.txt, but after saving, the file is named: _text.txt_. Additionally, the content of this saved file is displaying as: [object Object] Be ...

Chrome does not trigger the mouseenter event for disabled elements

After creating an Angular directive that automatically disables a button based on certain conditions, I encountered an issue when trying to display a tooltip upon hovering the disabled button in Chrome. Using the @HostListener directive, I implemented the ...

What is the method for generating a binary numpy array with two columns from a list of strings?

Input: A list of strings provided below: ['x', 'x', 'y', 'z', 'z', 'x', 'y'] Desired Output: I am looking to convert this list into a numpy array as shown: array([[ 1, 0, 0], ...

Is the Cyrillic encoding feature not functioning properly in Angular 4 with .Net Core 2?

Struggling with handling Cyrillic characters in my current project. Utilizing .Net Core 2 along with Angular 4.2.5 I've noticed that displaying a string in the templates using {{ someCyrillicString }} works fine. However, encountering issues when tryi ...

What specific type should be used for validations when incorporating express-validator imperative validations?

Having trouble implementing express-validator's imperative validations in TypeScript because the type for validations cannot be found. // reusable function for multiple routes const validate = validations => { return async (req, res, next) => ...

Saving user information in a MongoDB database with Node.js using a POST request

Currently, I am in the process of developing a web application using the MEAN stack along with Angular 6. One of the key functionalities is the ability to submit data into MongoDB via a form. Below is the function responsible for saving the extruded value ...

Using Angular to populate textboxes with SQL data

I am encountering an issue with a mat-table that retrieves its data from a database. One of the columns needs to be editable by the user so that they can update the content and reflect changes in the database. The problem lies in loading the data into the ...

Manipulating Website Content with jQuery Flexibility

I am new to web development and I'm attempting to create a dynamic page that pulls content from a MySQL database using PHP and stores it in arrays. The goal is to generate the page based on this data with the help of jQuery. However, the code I have p ...

Is it possible to maintain the scroll position of a PrimeNG table when updating the data?

I've encountered a challenge while working on a project involving PrimeNG 12 tables with Angular 12. The issue lies in Angular's change detection mechanism and updating table data, specifically in preventing a PrimeNG p-table from scrolling back ...

The data in the Angular variable is not persisting

After calling this function to retrieve an array of Articles, I noticed that the data is not being saved as expected. Take a look at my console output below. GetAll() { //return this.http.get<Array<Article>>(this.cfg.SERVER); this.http.get ...

Retrieve items from an array using indexes provided by a separate reference table

I am dealing with two different arrays. One array contains my data: var tab1 = ["one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen","twenty"]; ...

Unable to locate the necessary file. - Implementing TypeScript in a React application

Attempting to integrate TypeScript into an existing React app by following the steps outlined at: https://create-react-app.dev/docs/adding-typescript I've followed all the instructions but encountered the following error upon trying to launch the app ...

Configuring Spring Boot with Security to enable secure communication with an Angular web application

I currently have a spring boot application running on domain A. Its main purpose is to expose REST endpoints. In addition, I have an angular 8 application that can be deployed either on the same domain A or on another domain B. The spring boot app is able ...

Injecting shared libraries in a NestJs monorepo system

I am working on a NestJS application that consists of several microservices stored in a single repository following the monorepo approach. The AccessControl module is located in the libs directory and is meant to be shared across multiple microservices. I ...

Combining arrays within cells in excel

I am working with three single-cell arrays that do not contain any text (refer to ). A1 = {"A","B","C"} B1 = {"1","2","3"} C1 = {"X","Y","Z"} I am looking to concatenate them. D1 = "A 1 X , B 2 Y , C 3 Z" The formula should be able to work for larger ...