New data field is created with AngularFire2 update instead of updating existing field

I am facing an issue with updating a Firestore model in Angular 6. The model consists of a profile name and a list of hashtags. The "name" is stored as the value of a document field, while the "hashtags" are stored as keys in an object. However, every time I try to update the database entry, a new document field called "data" gets added instead of updating the existing fields.

How can I resolve this problem?

Here is how my Firestore structure looks before the update: https://i.stack.imgur.com/sHwrP.png

When I call the update function, it adds a new "data" field instead of updating the existing fields. https://i.stack.imgur.com/3ILLC.png

My Firestore Service:

export class MembersService {
  membersCollection: AngularFirestoreCollection<Member>;
  members$: Observable<Member[]>;
  memberDoc: AngularFirestoreDocument<Member>;

  constructor(public afs: AngularFirestore) {
    this.membersCollection = afs.collection<Member>('Members');
    this.members$ = this.membersCollection.snapshotChanges().pipe(
      map(actions => actions.map(a => {
        const data = a.payload.doc.data() as Member;
        const id = a.payload.doc.id;
        return { data, id };
      }))
    );
  }

   getMembers(): Observable<Member[]> {
     return this.members$;
   }

   updateMember(member: Member) {
    this.memberDoc = this.afs.doc(`Members/${member.id}`);
    this.memberDoc.update(member);
   }
}

My input component.ts:

export class MembersComponent implements OnInit {
  members: Member[];
  editState: boolean;
  membertoEdit: Member;

  constructor(private membersService: MembersService) {
    this.editState = false;
   }

  ngOnInit() {
    this.membersService.getMembers().subscribe(members => {
      this.members = members;
    });
  }

  editMember(member: Member) {
    this.editState = true;
    this.membertoEdit = member;
  }

  clearState() {
    this.editState = false;
    this.membertoEdit = null;
  }

  submit(member: Member, editName: string, editHashtag: string) {
    if ( editName !== '' && editHashtag !== '') {
      this.membertoEdit.name = editName;
      const key = editHashtag;
      const object = {};
      object[key] = true;
      this.membertoEdit.hashtag = object;
      this.membersService.updateMember(this.membertoEdit);
    }
    this.clearState();
  }
}

My component.html for the user Input:

<button *ngIf="editState == false" (click)="editMember(member)">edit</button>

<div *ngIf="editState && membertoEdit.id == member.id">
  <form>
      <input type="text"  #editName>
      <input type="text" #editHashtag>
      <button (click)="submit(member, editName.value, editHashtag.value);
        editName.value=''">Submit</button>
    </form>>
</div>

Answer №1

Figured out a solution: While it may not be the most elegant, you can pass each input individually

updateMember(member: Member, editName: string, editHashtag: object) {
    this.memberDoc = this.afs.doc(`Members/${member.id}`);
    console.log(this.memberDoc);
    this.memberDoc.update({
      name: editName,
      hashtag: editHashtag
    });
   }

submit(member: Member, editName: string, editHashtag: string) {
    if ( editName !== '' && editHashtag !== '') {
      const key = editHashtag;
      const object = {};
      object[key] = true;
      this.membersService.updateMember(member, editName, object);
    }
    this.clearState();
  }

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

Ensure child elements do not surpass parent size in HTML/CSS/Javascript without altering the children directly

I am intrigued by how iframes neatly encapsulate all site data within a frame and adjust it to fit the size. Is there any method to achieve this functionality in an HTML wrapper? Can the wrapper be configured so that regardless of the content, it is dis ...

How to send props from a Vue.js component tag in an HTML file

I'm facing an issue with passing props from the HTML to the JavaScript code and then down to a Vue component. Here's a snippet of my index.html file: <div id="js-group-discounts"> <div class="form-group required"> <datepick ...

The confirmation dialogue is malfunctioning

Need some assistance with my code. I have a table where data can be deleted, but there's an issue with the dialog box that pops up when trying to delete an item. Even if I press cancel, it still deletes the item. Here is the relevant code snippet: ec ...

What is the significance of incorporating 'Actions' as data within the Redux framework?

According to Redux documentation, creating actions and action creators is necessary. Here's an example: function addTodo(filter) { return { type: SET_VISIBILITY_FILTER, filter } } Next step is to write reducers, like this: function t ...

Can we access global variables directly in an Angular 2 HTML template?

After setting the app.settings as shown below public static get DateFormat(): string { return 'MM/DD/YYYY';} I need to utilize it in one of my HTML templates for a component. This is what I want to achieve. <input [(ngModel)]="Holiday" [dat ...

Is there a way to display a secondary header once the page is scrolled down 60 pixels?

.nav-header2{ background: purple; display: flex; justify-content: center; align-items: center; } .header2-container{ width: 68vw; height: 60px; padding: 0 2vh; border: 1px solid red; ...

Ways to determine changes made to a table in MSSQL

What is the most efficient method to determine if a table or row in MSSQL (using Node.js) has been modified? I am looking to verify whether my database has been updated within the past 30 minutes. If no updates have been made in the last half hour, I pla ...

AngularJS directive: handling child elements

Is there a way to structure the directive below in order to have access to all the ul elements within the link function? In the code snippet provided, when examining the elm (logged in console), it appears as a comment type and ul are displayed as sibling ...

An issue with the HTTP GET Request method is that it often sends "?" instead of "/"

I have a general method for interacting with my Swagger API: get<ReturnType>(url: string, params?: HttpParams): Observable<ReturnType> { return this.http.get<ReturnType>(environment.apiUrl + url, { params: params, }); } ...

Issues with importing files have been reported on Node.js version 11.8.0

I'm currently working on a program that utilizes a large object filled with dictionary words. I've decided to import this object from a separate file due to its size, but I encountered an error stating that Node.js doesn't recognize the obje ...

Encountering the error "Error: Maximum update depth exceeded" while coding a React private Route with infinite

Attempting to render components inside private routes only if the user is authenticated, but encountering an error message that reads: "Error: Maximum update depth exceeded." This issue typically arises when a component continuously calls setState within c ...

Incorporating an external module into your Angular application for local use

I currently have two projects: my-components, which is an Angular library, and my-showcase, an Angular app. Whenever I make changes or add a new component to my library, I commit it to a private git repository and publish it to a private npm registry. This ...

Angular is unable to iterate through a collection of ElementRef instances

My list of ElementRef contains all my inputs, but adding listeners to them seems to indicate that textInputs is empty even though it's not. @ViewChildren('text_input') textInputs!: QueryList<ElementRef>; ngAfterViewInit(): void { ...

The optional parameters could not be obtained

After reading through the Angular documentation, it seems that I should be able to retrieve a route's options parameters from route.paramMap. However, when I attempt to log out the params, I am getting an empty object in return. I am developing a log ...

The Angular single-page application fails to refresh when being executed via Visual Studio 2017 Community

I have encountered a problem with my angular 6 app not refreshing when running through Visual Studio 2017. The project consists of multiple projects, including a .NET Core 2 WebAPI and the angular app in question. Even after setting the startup to only be ...

Tips for maintaining interactivity after a page refresh

$(document).ready(function () { $("#2").click(function () { $("#content").load("{% url 'about' %}"); }); $("#3").click(function () { $("#content").load("{% url ...

Modify the data in a JSON array and receive the revised array using JavaScript

Within my JSON object, I have price values in numerical format. I am looking to convert these price values into strings within the same object My approach involves using the map function: var prods = [ { "id": "id-1", "price": 239000, "inf ...

Updating the image source attribute using Vue.js with TypeScript

Let's discuss an issue with the img tag: <img @error="replaceByDefaultImage" :src="urls.photos_base_url_small.jpg'"/> The replaceByDefaultImage function is defined as follows: replaceByDefaultImage(e: HTMLImageElement) ...

The most efficient method for retrieving data in React

Recently, I started working on a React App integrated with Riot API to display users' recent games and more. As part of this project, I'm utilizing React and NextJS (fairly new to NextJS). However, I'm contemplating the most efficient way to ...

Can you explain the significance of network activity groupings within the Firebug Net tab?

Can you explain the significance of different splitter lines on the Net tab in Firebug? In this screenshot, line 1 and 2 appear to be grouped together. However, line 3 stands alone. What do these groupings represent? ...