AngularFire UPDATE -> APPLY CHANGES

I can't seem to figure this out. I'm wondering how to UPDATE a document that is returned in the WHERE clause using AngularFire:

constructor(private db: AngularFirestore) { }

var path = this.db.collection('users').doc('type').collection('customer')
.ref.where('name', '==', 'roger');

How can I update this user?

var query = path.set/update..? 

It's not working as expected.

Answer №1

The acceptance of the previous answer raises concerns as it seems to lead to incorrect behavior, resulting in an infinite loop (snapshotChanges() triggering update(), which then triggers another snapshotChanges() due to subscribing.) Additionally, the AngularFirestore syntax mentioned appears to be outdated, prompting the need for a different approach.

To address the desired behavior by the original poster (OP), it is advised to store the document ID within the document itself. When adding a new item, the use of add() provides a DocumentReference that contains the newly inserted item's ID.

An effective implementation example would involve:

 create(user) {
    return new Promise<any>((resolve, reject) => {
      this.db
        .collection('users')
        .doc('type')
        .collection('customer')
        .add(user)
        .then(res => {
          this.updateUserId(res.id);  
        }, err => reject(err));
    });
  }

  updateUserId(id: string) {
    return this.db
      .collection('users')
      .doc('type')
      .collection('customer')
      .doc(id)
      .set({ id: id }, { merge: true });
  }

In this scenario, the user is first created, followed by updating the id field of the user object immediately (as the Firestore document ID becomes available post insertion). This enables easy subsequent updates based on the user’s document ID.

Answer №2

Here is a solution for your query: run the code below to retrieve a list and update the IDs accordingly.

const query = this.db.collection('users').doc('type').collection('customer', ref => ref.where('name', '==', 'roger'));

query.snapshotChanges().map(changes => {
   changes.map(a => {
    const id = a.payload.doc.id; 
    this.db.collection('users').doc('type').collection('customer').doc(id).update({})
  })
}).subscribe();

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 best way to merge the data from a resolver into a combineLatest function?

I'm facing an issue with my resolver that returns an Observable<Product[]> on a page to load data. After that, I try to combine this stream with another using combineLatest. However, the problem arises when combining the streams as I receive an ...

Implementing secure access control in Angular based on user roles

Currently, we are working on integrating role-based security with Angular. However, we are looking for a solution to implement this on the server side to prevent users from accessing the page by manipulating JavaScript code in their browsers. While our se ...

What is the best way to incorporate ControlContainer in an Angular component's unit test?

Is there a way to include ControlContainer in an Angular unit test? The error message I am encountering reads: NullInjectorError: StaticInjectorError(DynamicTestModule)[ChildFormComponent -> ControlContainer]: StaticInjectorError(Platform: core) ...

Employing a boolean constant to verify if a parameter has been specified

Struggling with TypeScript version 2.8.3, I'm confused as to why the code below is failing to recognize that params is defined inside the if block. const testFunction = (params?: string) => { const paramIsDefined = typeof params !== 'undefi ...

Previewing files from external URLs with Ionic 5 Capacitor and Angular

I recently implemented the previewanyfile cordova plugin in my Ionic 5 application to open files from external URLs. While it works smoothly on Android devices, I have encountered an issue on iOS where some PDF files fail to preview and instead display a g ...

Utilize Angular2 to dynamically add new routes based on an array register

Currently, I am utilizing Angular2 for the frontend of my project and I am faced with the task of registering new Routes from an array. Within my application, there is a service that retrieves data from a server. This data is then stored in a variable wit ...

Expanding properties in a React component based on certain conditions using TypeScript

I am attempting to dynamically expand my component props based on whether a specific prop is included. The goal is to add attributes from an anchor if the href prop is provided, and include attributes from a button if it is not. Is this achievable? Chec ...

Facing issue with Angular 17 where pipe is displaying empty data

I am currently utilizing Angular 17 with the code provided below: database.component.html @for(user of (users | userPipe:filters); track user.id) { <tr id="{{ user.id }}"> <td>{{ user.name }}</td> <td> ...

Ensure that the query value remains constant in Express.js

Issue: The query value is changing unexpectedly. // url: "http://localhost:4000/sr?q=%C3%BCt%C3%BC" export const search = async (req: Request, res: Response) => { try { const query = String(req.query.q) console.log("query: &quo ...

There was an error due to a TypeError: The 'page' property cannot be read because it is undefined

Can anyone assist me with an Angular issue I'm facing? I've been working on integrating server-side pagination, but no matter how many times I revise my code, I keep encountering the same error message: ERROR TypeError: Cannot read properties o ...

What is the best way to set the minDate and maxDate of the NgbDatePicker in the main component so that the settings can be applied

Within my Angular 4 project, I have integrated Ng-bootstrap (v1.1.0) which includes multiple date pickers across different modules. I am looking to enforce a global maxDate configuration for all these instances. Below is an overview of my folder structure: ...

The Angular Material Table is not showing any data on the screen

My challenge is to consolidate data from 4 different endpoints in order to generate a ListElement that will populate an angular material table. Despite receiving the correct data in my logs, the table remains empty. Interestingly, when I include a conditio ...

What is the best way to set up an empty {[key: string]: string} object in TypeScript?

interface a { d: {[key: string]: string} } class a { d = {} } The error message returned is as follows: Subsequent property declarations must have the same type. Property 'd' must be of type '{ [key: string]: string; }', but ...

Troubleshooting Cross Origin Error in C# and Angular

We are currently in the process of developing a website using Angular 5. The backend has been created utilizing .Net Web API and SQL Server. Our plan is to deploy the website on Azure, making it accessible both from the internet and the intranet. After co ...

Removing Firebase Users using Angular2/Ionic2

I'm currently working with Ionic2/Angular2 and I've been searching for a guide on deleting users from Firebase. If anyone has any useful examples, I would greatly appreciate the assistance. Thank you. ...

Using the spread operator to modify an array containing objects

I am facing a challenge with updating specific properties of an object within an array. I have an array of objects and I need to update only certain properties of a single object in that array. Here is the code snippet I tried: setRequiredFields(prevRequir ...

What is the reason for the allowance of numeric keys in the interface extension of Record<string, ...>

I am currently working on a method to standardize typing for POST bodies and their corresponding responses with API routes in my Next.js application. To achieve this, I have created an interface that enforces the inclusion of a body type and a return type ...

What is the best way to remove a specific row from an Angular Material table that does not have any filters

Here is my samplepage.component.ts code: import { Component } from '@angular/core'; @Component({ selector: 'app-batchticketvalidation', templateUrl: './batchticketvalidation.component.html', styleUrls: ['./batchtic ...

What steps should I take to create a consistently pristine and efficiently operating Angular 2 setup?

Currently mastering Angular 2 and making significant progress. However, encountering issues when attempting optimized builds with tree shaking. Constantly receiving error explosions deep within the Angular code. These errors may stem from bugs in Angular/n ...

Utilizing the Double Mapping Feature in React with Typescript

It seems I might be overlooking something, can someone guide me on how to properly double map in this scenario? I'm encountering an error on the second map: Property 'map' does not exist on type '{ departure: { code: string; name: strin ...