Is there a different way to update data in AngularFireStore using alternative syntax or logic

I am seeking alternative methods for implementing Update data in Firestore within a component's typescript file.

Typically, I would utilize a service and subscribe to it, but due to performance issues caused by loading around 20,000 records during a data migration process, our app has been crashing.

In the usual way, I would do the following:


Via Service:


import { Injectable } from '@angular/core';
import { AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument} from '@angular/fire/compat/firestore';
import { Observable } from 'rxjs';
import {map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})

export class CustomerService {
  customerCollection: AngularFirestoreCollection <Customer>;
  customerDoc: AngularFirestoreDocument <Customer>;
  customers: Observable<Customer[]>;

   constructor(
    public angularFireStore: AngularFirestore

  ) 
  {}

    getCustomer() {
    this.customerCollection = this.angularFireStore.collection('customer');
    this.customers = this.customerCollection.snapshotChanges().pipe(map(changes => {
      return changes.map( a => {
        const data = a.payload.doc.data() as Customer;
        data.id=a.payload.doc.id;
        return data;
      })

    }))
    return this.customers;
  }

  addCustomer(customerAdd:Customer) {
    this.customerCollection.add(customerAdd);
  };

  updateCustomer(custcol : Customer) {
    this.customerDoc = this.angularFireStore.doc(`customer/${custcol.id}`);
    this.customerDoc.update(custcol);
  }


}

Traditionally, in my Component TS Old Code, I would simply include the update logic in a function like this.

 customerList: customerModel[];
 customerDetails : customerModel;
 customerName: any;
 
 addCustomer : Customer ={
    customerNo: '',
    customerAccountNo: '',
    customerName: '',
    customerAddress: '',
    customerContactNo: '',
    customerEmail: ''

  };

ngOnInit(): void {
 this.customerService.getCustomer().subscribe( customerObservable => {
 this.customerList = customerObservable});
}


add() {
 this.addCustomer.customerName = this.customerName //(input comes from ngModel btw)
 this.customerCollection.add(this.addCustomer);
}

update(){
 this.customerDetails.customerName = this.customerName //(input comes from ngModel btw)
 this.customerService.UpdateCustomer(this.customerDetails)
}

This setup was efficient with only 6000+ records, but after adding more data, it became sluggish. In search of solutions, we have moved away from using the service and integrated everything into the component instead. Although I successfully implemented the Query (using ValueChanges), and Adding, I am struggling to find proper documentation or syntax for the Update operation, even on the official AngularFireStore Documentation.

Here is my updated Component TS Code

import { AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument } from '@angular/fire/compat/firestore';
import { Observable} from 'rxjs'; 
import { Customer } from '../../models/customer.model';


@Component({
  selector: 'app-add-client',
  templateUrl: './add-client.component.html',
  styleUrls: ['./add-client.component.scss']
})
export class AddClientComponent implements OnInit {

 private customerCollection: AngularFirestoreCollection<Customer>
 private customerDocs: AngularFirestoreDocument<Customer>
 customers: Observable<Customer[]>
  
 constructor(
    public afs: AngularFirestore
  ) { 
    this.customerCollection = this.afs.collection<Customer>('customer')
    this.customers = this.customerCollection.valueChanges();
  }
 customerList: Customer[];
 customerDetails: Customer;

 addCustomer : Customer ={
    customerNo: '',
    customerAccountNo: '',
    customerName: '',
    customerAddress: '',
    customerContactNo: '',
    customerEmail: ''
 
  };

queryCustomer() {
    
    this.customerCollection = this.afs.collection('customer',
    ref => ref
    .orderBy('customerName')
    .startAt(this.query)
    .endAt(this.query + "\uf8ff"));
    this.customers = this.customerCollection.valueChanges();
    this.customers.subscribe(
     (data) => (this.customerList = (data)));
  }

add() {
  this.addCustomer.customerName = this.customerName;
  this.customerCollection.add(this.addCustomer);
}

queryCustomer() {
    
    this.customerCollection = this.afs.collection('customer',
    ref => ref
    .orderBy('customerName')
    .startAt(this.query)
    .endAt(this.query + "\uf8ff"));
    this.customers = this.customerCollection.snapshotChanges().pipe(map(changes =>{
        return changes.map(a =>{
        const data=a.payload.doc.data() as depositModel;
        data.id=a.payload.doc.id;
        return data;
       });
      }
    ));
    this.customers.subscribe(
     (data) => (this.customerList = (data)));
  }


}

I have made several attempts at updating the records, but none seem to work correctly.


update() {
 
  this.customerDocs = this.angularFirestore.doc(`jobOrders/${customerDetails.id}`);
  this.customerDocs.Update(customerDetails);

}


I am relatively new to this type of implementation and would greatly appreciate any assistance. Thank you.

Answer №1

As highlighted in the first example and second example, updating data can be achieved using the following methods:

Example 1 :

onRename() {
        if (!this.editForm.value.replaceValue) {
            this.message = "Field cannot be empty!";
        } else {
            this.firestore.collection('testCollection').doc(this.id).update({ field: this.editForm.value.replaceValue });
            this.edit = false;
            this.message2 = '';
            this.single = null;
        }
    }

Example 2 :

updateCoffeeOrder(data) {
   return
       this.firestore
       .collection("coffeeOrders")
       .doc(data.payload.doc.id)
       .set({ completed: true }, { merge: true });
}

For further reference, you can visit the Stack Overflow post or watch a detailed video on CRUD operations.

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

develop a drag-and-drop sortable list using Angular 5 and ng-bootstrap

I have completed most of the development for my app, but the final task is to implement a feature that allows users to rearrange a list of items in different orders and save the changes. My app is built using angular5 (cli) and ng-bootstrap. Is there a wa ...

Import a JSON file into TypeScript declaration files (*.d.ts)

I am currently working on a declaration file where I need to establish a global type that is specifically tied to a predetermined list of string phrases. These string phrases are part of property keys within an object located in a JSON file. I have a coup ...

There is no assigned value in scope for the shorthand property. You must either declare one or provide an initializer

I'm just starting out with TypeScript. Encountering the error 'No value exists in scope for the shorthand property 'firstName'. Either declare one or provide an initializer.' while using Prisma with Next.js to create a new user in ...

Error Message: The Reference.update operation in Angular Firebase failed due to the presence of undefined value in the 'users.UID.email' property

Having recently started to use the Firebase database, I encountered an issue while trying to update the UID to the Realtime Database during signup. The error message displayed was: Error: Reference.update failed: First argument contains undefined in prop ...

How come the inference mechanism selects the type from the last function in the intersection of functions?

type T = (() => 1) & (() => 2) extends () => infer R ? R : unknown What is the reason that T is not never (1 & 2)? Does the type always come from the last function, or can it come from one of them? ...

Fill the image with width using Mat

While working on creating cards using Angular Materials, I encountered an issue where the image was not filling up the space as desired. The red area in the image indicates where I want the image to take up space. https://i.sstatic.net/vcc9U.png HTML: & ...

How to Implement checked radio buttons in Angular 2 using ngModel

When generating radio buttons in Angular, I am using the following code: <div class="radio" *ngFor="let gender of genders"> <input type="radio" name="gender" [checked]="gender=='male'" [value]="gender"> {{gender}} </div> ...

When using mongoose.save(), the data is not stored successfully

I spent 5 hours trying to solve this problem but couldn't figure out what's wrong in the file -routes/users.ts, The line ""targetUser.token = token" is working, so console.log(targetUser) shows the updated user data. However, targetU ...

Angular4 paired with Bootstrap 4 creates a sleek and stylish footer positioned at the bottom of the

I have already done extensive research on Google and this board, trying numerous solutions without success. My goal is to have a footer positioned at the bottom of every site, even if the site does not reach the bottom of the viewport. Using Angular4 and ...

Ionic 2: Issue with Action Sheet transitioning to Tab Page

In my Ionic 2 framework project, I am using a component action sheet. However, when I click on the locator button, the back button does not work as expected. locator-tab.ts import {Component} from '@angular/core' import {firstLocator} from &apo ...

Updating content in Angular 4 X-editable form does not reflect changes in form value

Having trouble with the jQuery X-editable library in an Angular 4 environment. Here's the code snippet: model.html <a href="javascript:;" onClick="event.stopPropagation(); event.preventDefault();" editableToggle="#editable{{selectedModel.id}}"> ...

The latest version of npm Boostrap (4.1.0) is missing some important CSS properties for the `background` tag

I am currently working on an Angular 5.2.10 project that utilizes angular-cli and bootstrap version: 4.0.0-beta.2 with a specific css class called .en-icon-24: .en-icon-24 { background: url(../../../../assets/img/icons.png) -370px 0px; width: 24 ...

How can variables within nested ngFor loops be referenced in Angular 1.5 compared to Angular 10?

This particular piece of code was functional in Angular 1.5. It featured a condition where the <tr> element would only be displayed if the 'showFields' flag for that specific row key was set to true. <table> <ng-container *ngIf=& ...

Tips for creating a console.log wrapper specifically designed for Angular2 using Typescript

Is there a way to create a custom global logging function in Angular 2 TypeScript project that can be used instead of console.log for services and components? I envision the function looking like this: mylogger.ts function mylogger(msg){ console.log ...

Data entered into DynamoDb using typedORM displays inaccurate Entity details

Whenever I add new entries to my local dynamoDb table using typeDORM within a lambda function, it seems to save the record with the incorrect entity information. For example, the GSI1PK GSI1: { partitionKey: 'PRO#{{primary_key}}', ...

Instructions on how to modify a document's content by its unique identifier using Firebase Modular SDK (V9)

I am trying to figure out how to update an existing document for the same user ID in V9 Firebase whenever they log in, rather than creating a new one each time. Any suggestions on how to achieve this? Current Code setDoc( query(collectionRef), // ...

Package name "@nx-cloud" is invalid as it does not meet the requirements for Nx 16

Whenever I attempt to install a package in my project, I encounter the following error message: Invalid package name "@nx-cloud" of package "@[email protected]": name can only contain URL-friendly characters. Could this issue be ...

Angular 6 causing functionality issues with Angular2-JWT package due to RXJS import problems

Recently, I encountered some challenges with a package called Angular2-jwt while transitioning an existing application to Angular 6. The errors being thrown are as follows: Module not found: Error: Can't resolve 'rxjs/Observable' in 'C ...

Unable to open modal externally without encountering an error in MaterializeCSS

I'm currently facing an issue with a standard modal that pops up at the bottom of the page. I have a function that generates multiple components on the page, each with a 'play' button. When this button is clicked, it triggers a function pass ...

Issue C2039: 'IsNearDeath' cannot be found within 'Nan::Persistent<v8::Object,v8 ::NonCopyablePersistentTraits<T>>'

After updating my nodejs to v12.3.1, I encountered errors when attempting to execute npm install in my project directory. error C2059: syntax error: ')' (compiling source file ..\src\custo m_importer_bridge.cpp) error C2660: 'v8 ...