How can I retrieve the index of an object within an array stored in Firestore?

I am currently working with Ionic and Firebase Firestore. My goal is to implement a functionality where users can click on a specific ion-card containing an object, triggering a method to display an ion-action-sheet with a Delete button. This would allow them to delete the selected object, which is stored in an array within Firestore.

Here is an overview of the data structure:

This snippet shows the current HTML file pertaining to the ion-card:

<ion-card class="lightCard" *ngFor="let reviews of revArr" (click)="selectReview()">

        <ion-card-header>
          <ion-grid>
            <ion-row>
              <ion-icon name="person-circle-sharp" class="profIcon"></ion-icon>
              <ion-card-title class="cardUsername fontWhite" style="font-size: 35px;">{{reviews.userName}}</ion-card-title>
            </ion-row>
          </ion-grid>
          
        </ion-card-header>
          
        <ion-card-content class="font cardContent">
          <h1 class="title" style="font-weight: bold;">{{reviews.title}}</h1>
          {{reviews.review}}
        </ion-card-content>
      
      </ion-card>

Below is the code within the corresponding class:

  ngOnInit() {
    const compId: string = this.route.snapshot.paramMap.get('id'); //get id

     //for reviews array in `reviews`
    this.reviewCollection = this.afStore.doc(`reviews/${compId}`)
    this.rev = this.reviewCollection.valueChanges().subscribe(item =>{
    this.revArr = item.reviews
    this.userNrev = item.reviews.userName
     })   
  }

  async selectReview(){
  
    const actionSheet = await this.actionSheetCtrl.create({
      header: "Delete "+ this.userNrev + "'s review?",
      buttons: [
        {
          text: 'Delete',
          handler: () => {
           //delete code
          }
        }
      ]
    })
    await actionSheet.present();
  }

The main question at hand revolves around obtaining the index from the Firestore array and utilizing it for deleting the respective object.

I would greatly appreciate any assistance as I am still relatively new to these concepts.

Answer №1

Firebase advises against using arrays because it can lead to data corruption when multiple users update the array simultaneously.

It's worth noting that a firebase document has a maximum size of 1mb. If you have lengthy reviews, you may reach this limit and end up loading a large file each time.

In this scenario, modifying the array in your code and updating the entire field may be necessary.

A more effective approach would involve using a subcollection, with each review being its own document. This way, you can easily fetch a limited number of reviews at a time (using limit()) and make updates or deletions effortlessly.

For more information, check out the official YouTube series on Firestore and how to organize it by following this Link.

Answer №2

Your strategy is not aligned with your objectives:

  • If you simply need to save a random list of data, an array within a single document can suit your purpose perfectly.
  • However, when the intention is to store data for future manipulation (such as deletion or updating), it's best practice to have each entry in its separate document - one review per document. This approach facilitates managing and modifying individual reviews or even batches of reviews more efficiently and reliably.

To learn how to correctly utilize Firestore, watch this video tutorial here. It covers Firestore usage with Angular, which could be beneficial for advancing your understanding.

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

`ng-apexcharts` causing unit test failures

I've been working on integrating apexcharts and ng-apexcharts into my home component. While I was able to get it up and running smoothly, it seems to be causing issues with my unit tests. Despite researching possible solutions, I haven't been abl ...

Is it possible to incorporate JavaScript files into a TypeScript (ts, tsx) project that has already been built?

Recently, I was given a task to incorporate additional pages into the current project which has been developed using the following technologies: Laravel: 8.12 React: 17.0.2 NextJS: 10.0.9 Tailwind CSS: 2.0.4 React Query: 3.13.0 [ REST] TypeScript: 4.2.3 M ...

How to perform complex relational queries in TypeORM using relationship properties?

Currently, I am immersing myself in Nest.js using TypeORM and exploring its query builder capabilities. I recently came across the relations property, which proved to be quite useful. However, I'm wondering if it's possible to achieve the same o ...

Building Firestore subcollections with the latest WebSDK 9: A step-by-step guide

I'm looking to create a subcollection within my document using the webSDK 9, specifically the tree-shakable SDK. While I have come across some solutions, they all seem to be outdated and reliant on the old sdk. Just for context, I am working with Ne ...

Explore the potential of utilizing Reactive Forms in conjunction with storybook templates

Currently, I am working on developing some custom components and form elements that I intend to include in Storybook. To ensure completeness, I want the stories to utilize FormControl and FormGroup to demonstrate a real-world use case. Here is an example ...

Re-activate a disabled Angular mat-select field

I am facing an issue with a mat-select field on a form that serves dual purposes. Firstly, it is used to select specific values to include in a data element when searching for records. Secondly, once a record is found, it displays the value of the data ele ...

Tips for implementing UI properties in React

Utilizing an external UI Library, I have access to a Button component within that library. My goal is to create a customized NewButton component that not only inherits all props from the library Button component but also allows for additional props such as ...

Having trouble opening a JPEG file that was generated using the Writefile Api in Ionic-Cordova

Currently, I am using the writeFile API to create a JPEG image. The process is successful and the image is stored in the directory as expected. However, when I try to open the file manually from the directory, I encounter an error message saying "Oops! Cou ...

Error Encountered When Trying to Import BrowserAnimationsModule in Angular 5: Unexpected Token "<"

As I try to integrate the BrowserAnimationModule into my Angular 5 project, a rather foolish error keeps popping up. Error: (SystemJS) Unexpected token < SyntaxError: Unexpected token < at eval (<anonymous>) at Object.eval ...

Tips on configuring a segment in an Angular 6 route

Question: I am looking to configure a specific segment after the user logs in, for example http://localhost:4200/#/{dynamic name}/{dynamic name}/app/... However, I am facing an issue when navigating to /app/... across the application. Is there a way to a ...

What is the best way to switch from using 'arguments' in JavaScript to Typescript?

I have a situation where I need to implement a method that gets called whenever the push operation is performed on an array. How should I approach this in typescript? My attempt so far: addEvent(myArray) { let _this = this; myArray.push = functi ...

What is the best way to define a property that only exists under certain conditions?

After the server responds, it will look like this: { code: number; info: string; data //appears only when code is 200 } How can I create a type definition to specify that the data property should only exist when code is 200? My current code i ...

Is there a way for me to retrieve the value that has been set within the cy.get() function in Cypress using Typescript?

Is there a way to retrieve the value of the getLength function without it returning undefined? How can I access the value in this case? Here is my code snippet: const verifyValue = () => { const selector = 'nz-option-container nz-option-item&apo ...

Utilize the URL path entered by a user to navigate through the page

I'm exploring Angular 6 to develop my app and I need a feature that can grab whatever the user is typing into the address bar on the website. For instance: If a user types in the domain "myproject.example/5/cool", the site should display "User 5 is ...

methods for array filtering in typescript

How do I filter an array in TypeScript? I attempted the following findAllPersonsNotVisited():Observable<Person[]> { var rightNow = new Date(); var res = rightNow.toISOString().slice(0,10).replace(/-/g,"-"); return this.db.list(& ...

Error encountered while attempting to inject a store into a React application using Typescript

Currently, I am working on building a React app with TypeScript and using Redux for state management. However, I encountered an error related to the app component. https://i.sstatic.net/zetyR.png -app.tsx import React from 'react'; import { Pro ...

Do not include the node_modules directory in the TypeScript compilation process, except for a specific subdirectory that is

To exclude the entire node_modules directory from TypeScript compilation, you can modify the tsconfig.json file like so: { "compilerOptions": { "module": "commonjs", "sourceMap": true, "target": "es6" }, "exclude": [ ...

When selecting a dropdown in Angular 5, the aria-expanded attribute remains unchanged and the 'show' class is not applied. This behavior is specific to Bootstrap dropdowns

Having an issue with the bootstrap dropdown in my Angular project. When I click on it, the dropdown-menu does not show up. The 'show' class is not being added to the dropdown and the 'aria-expanded="false"' attribute does not change to ...

The property of the Angular Typescript object is distinctly not defined, yet the property itself is

Currently facing a bizarre issue. Even though the console displays data in an object from a subscribed observable, TypeScript code shows it as undefined. Take a look: initData(): void { this.backendService.getData().subscribe((depotDays: DepotDayAcc ...

What could be the reason behind Typescript's unexpected behavior when handling the severity prop in Material UI Alerts?

Trying to integrate Typescript into my react project and encountering a particular error: Type 'string' is not assignable to type 'Color | undefined'. The issue arises when I have the following setup... const foo = {stuff:"succes ...