Angular Firebase Update: Modify a certain field for each user in the database

As a newcomer to Angular and Ionic, I am trying to update a specific field for a user. My goal is to retrieve all the data from Firebase and update only one field. I have successfully accomplished this for a single logged-in user, but I am facing difficulties when trying to do it for all users.

export class AdminPage implements OnInit {
user:any;
userId:string;
enableAccess:boolean;
  constructor(
    private auth:AuthService, 
    private router:Router, 
    private afs:AngularFirestore,
    private loadingCtrl:LoadingController,
    private toastr:ToastController) { }

  ngOnInit() {
    this.auth.getAllUser().subscribe(user=>{
      this.user=user;
    })
    this.auth.user$.subscribe(user=>{
      this.enableAccess=user.IsApproved;
    })
    
  }
  async updateUserInfo(){
    const loading=await this.loadingCtrl.create({
      message:'updating',
      spinner:'crescent',
      showBackdrop:true
    })
    loading.present()
    this.afs.collection('user').doc(this.userId).set({
      'IsApproved':this.user.enableAccess
    },{merge:true}).then(()=>{
      this.toast('update sucessful','success');
    }).catch(error=>{
      loading.dismiss();
      this.toast(error.message,'danger');
    })
  }
  async toast(message,status){
    const toast =await this.toastr.create({
      message:message,
      color: status,
      position: 'top',
      duration:2000
    });
  }
}

component

ion-content>
  <ion-card>
      <ion-item> 
        <ion-label position="floating">Email:</ion-label>
        <p></p>
      </ion-item>

      <ion-item>
        <ion-label position="floating">Enable Access:</ion-label>
        <ion-input
          required
          type="boolean"
          [(ngModel)]="enableAccess"
          name="enableAccess"
        ></ion-input>
      </ion-item>
      <ion-button
        type="submit"
        expand="block"
        shape="round"
        (click)="updateUserInfo()"
        >Update</ion-button
      >

  </ion-card>
</ion-content>

I am looking to display the email of each user in the database and allow the admin to only update the enableAccess field. How can I retrieve all users and update this field?

Answer №1

If you need to fill in data for existing users, consider using a one-time node.js script instead of modifying the client-side application code.

For example, in node.js:

const admin = require("firebase-admin");
admin.initializeApp(...);

const db = admin.firestore();
db.collection("user").get((snapshot) => {
  snapshot.forEach((doc) => {
    doc.ref.update({ IsApproved: false });
  });
});

If you must do this on the client-side, it would be similar. Since this won't immediately affect the UI, it's best to use JavaScript and the regular SDK for the backfill process.

Even if the updates are displayed in the Angular UI, AngularFire works seamlessly with the JavaScript SDK. Updates made through the JavaScript SDK will still reflect in AngularFire without any issues.

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

Exploring Function Type in TypeScript: Utilizing both fat arrow and object literal type

Currently delving into the world of Typescript, I came across two methods for defining function types: using a fat arrow or an object literal. Here's an example: let myAdd1: (x: number, y: number) => number = function(x: number, y: number): n ...

Tips on organizing a typescript object/StringMap in reverse order to prioritize the last element

I've just started working with TS/React in a .tsx file and I'm trying to add a key/value pair to a StringMap at the very first index. Below is the code snippet that: takes the StringMap 'stats' as input, iterates through each row, re ...

Exploring the DOM in JavaScript: Searching for the final ancestor containing a specific attribute

Check out this example of HTML code: <div id="main1" data-attribute="main"> <div id="section2" data-attribute="subsection"> <div id="nested3" data-attribute="sub-subsection"> </div> </div> </div> <div id= ...

What is the reason why the swiper feature is malfunctioning in my React-Vite-TS application?

I encountered an issue when trying to implement Swiper in my React-TS project. The error message reads as follows: SyntaxError: The requested module '/node_modules/.vite/deps/swiper.js?t=1708357087313&v=044557b7' does not provide an export na ...

Anonymous function's return type

Looking for advice on an anonymous function I've written: static oneOf(options: any[], cb?: Function) ValidatorFn { .... } I'm a TypeScript beginner and unsure how to specify that the 'cb' must return a boolean. Can this be done, an ...

What is the best method for displaying a view on a new page in Angular 2?

Currently, I am facing a challenge with my Angular 2 project. I am struggling to figure out how to make a route open a new view instead of simply rendering in the same page. My goal is for the route to lead to a completely separate view rather than stayi ...

Azure Blob - uncovering the secrets of your storage activity

Our Angular App is currently being stored in Azure Blob. We are interested in viewing a list of requests that have been made to Azure Blob in the past few hours/days/... We would like to see details such as client IP, timestamp, requested item, transacti ...

Adding color dynamically to text within ion-card based on a regex pattern

My goal is to enhance the appearance of certain text elements by wrapping them in a span tag whenever a # or a @ symbol is detected, creating the look of usernames and hashtags on Twitter. Below is the code I am currently using: TS FILE: ngOnInit(): void ...

Using Angular to transmit data to a transcluded component

Is it possible to have a video-uploader component where users can upload one or multiple videos, with the ability to choose from three different view options: Seperate - In progress videos and uploaded videos are displayed in separate tables. Combine ...

I'm curious about how to implement textarea functionality within Angular for modeling purposes

I have a desire to utilize the model and transmit it to the server. One instance of this is sending comments. comment.model.ts export interface Comment { article_no: number; username: string; nickname: string; creatat: Date; content: string; } ...

Is there a way to incorporate margins into a React component using TypeScript?

I am currently facing a challenge in passing CSS attributes to a component that I am working with. The reason behind this is that I need to modify the margins to fit a specific space, hence my attempt to directly pass the margins. Does anyone have any sug ...

A step-by-step guide on generating a single chip using the same word in Angular

I'm trying to find a solution to ensure that only one chip is created from the same word inputted, instead of generating duplicates. Currently, users can input variations such as "apple," "APPLE," "apPPle," "aPpLe," and I want to automatically conver ...

Unable to receive FCM Push Notifications for web when testing on local server

I am currently working on implementing web push notifications in our web app. I have successfully set up Firebase Cloud Messaging in my app by following the documentation. I am able to prompt the user for permission to receive notifications and obtain the ...

Can sweetalert2 be used as a tooltip?

I have a query, is it feasible to include a tooltip in the alert message? Alternatively, could there be another tooltip option available? Swal.fire({ title: '<strong>An example with HTML tags</strong>', icon: 'info', ...

What is the best way to remove unnecessary scrollbars from a material dialog that includes a radio-group?

Check out this Stackblitz demo that showcases a dialog with a radio group inside the mat-dialog-content div. Notice how the dialog-content displays an unsightly scrollbar: https://i.sstatic.net/gvqlH.png This issue doesn't occur with other compon ...

Having trouble getting anime.js to function properly in an Ionic 3 project?

I have been attempting to incorporate anime.js into my Ionic 3 project, but I keep encountering an error when using the function anime({}) in the .ts file. Error: Uncaught (in promise): TypeError: __webpack_require__.i(...) is not a function TypeError: _ ...

Angular 8: Setting the Default Dropdown Option to the Newest Value in the Updated ArrayList

I am currently working with Angular 8 and TypeScript. After calling a service and updating the array collection, I want to automatically select the last aggregated value. However, I always want the placeholder to be shown. How can I achieve this? <nb- ...

Troubleshooting an issue with asynchronous reactive form validators in Angular

I encountered an issue where I need to access a service that sends an http request to an API to verify the existence of a given username. Snippet from Auth component: usernameCheck(username: string){ return this.http.get(this.baseUrl + "usernamecheck?u ...

Updating Items in Angular Does Not Automatically Refresh Validity

I'm encountering an issue where even after submitting the form with a value, the error message "field is required" persists when it should disappear. Do you think there could be a problem with my validity check? You can take a look at this link for re ...

Issues with routerLinkActive

On my page, I have a menu that uses the routerLinkActive attribute to add a green background when a link is active and grey when it's not. However, I'm facing an issue where the bg-success class is added but doesn't overwrite the bg-dark cla ...