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

Is there a way to print messages to the console of openDevTools in Electron JS?

After finishing a hello world application using electron js, I have successfully printed to my terminal with console.log and opened the openDevTools in the window of my application. However, I am now interested in finding a way for my console.log stateme ...

Choose a value to apply to the dropdown menus

I've encountered an issue with the following code - it only seems to work once and not every time: var selectedVal = $('#drpGender_0').find("option:selected").text(); if (selectedVal == "Male") { $('#drpGender_1').fi ...

import error causing an angular application to crash even with the module installed

Is there a possibility that an error is occurring with the import statement even though the syntax is correct and the required library has been installed? Could the issue lie within the core settings files, specifically the ones mentioned below (package.js ...

Tips for creating horizontal dividers with CSS in Vuetify using <v-divider> and <v-divider/> styling

Currently, I am working on a project using Vue.js and adding Vuetify. However, I need to use a component. .horizontal{ border-color: #F4F4F4 !important; border-width: 2px ; } <v-divider horizontal class=" horizontal ...

Elements Fail to Display After Updating State with UseState

This question presents a challenge due to its complexity, but I will try to clarify the situation before delving into the code implementation. My aim is to create a screen for managers displaying all their drivers with minimal information and an edit butto ...

Instructions on how to navigate back one page to determine which page initiated the action

I am looking for a solution to implement a back button that takes me back one page while caching it. Currently, I am using the following code: <a id="go-back" href="javascript:history.go(-1)" type="button" class="btn btn-danger">Back</a> Howe ...

Leveraging the identical data synchronously within the same useEffect block

My task involves fetching data in two different ways and rendering it accordingly. Initially, I need to retrieve each item one by one and increment the count. Once that is done, I should fetch all the data at once and update the display. To achieve this, I ...

Utilizing a functional component to incorporate a "load more" button in ReactJS

Hey everyone, I've come across this ReactJS code that I need some help with: function DisplaySolutions({solutions}) { const topSolutions = solutions.slice(0, 4); const remainingSolutions = solutions.slice(4); const [isD ...

Delay in input bar after extensive user engagement

I've been grappling with a perplexing issue for quite some time now, and it's proving to be quite elusive. In my Angular webshop, the product overview page features a product component with a lazily loaded, highly compressed image, a title, quan ...

implementing the CSS property based on the final value in the loop

I have created multiple divs with a data-line attribute. I am trying to loop through each div, extract the individual values from the data-line attribute, and apply them as percentages to the width property. However, it seems to only take the last value an ...

What is the most efficient method for retrieving an element using a data attribute with an object (JSON) value?

Imagine having the following HTML element: <div class='element' data-info='{"id":789, "value":"example"}'></div> By running this JavaScript code, you can access the object stored in the data attribute. console.log($(&apos ...

Encountered a React TypeScript issue stating that the type '{ ... }' cannot be assigned to the type 'IntrinsicAttributes & IntrinsicClassAttributes<...>'

Embarking on a new journey with a react typescript project, I encountered this puzzling error: Failed to compile. /Users/simon/Code/web/react-news-col/src/MainNewsFeed.tsx TypeScript error in /Users/simon/Code/web/react-news-col/src/MainNewsFeed.tsx(27,35 ...

Is the input in the array? How to find out?

I am currently facing an issue with a script that I have created to count array elements matching a user input. Strangely, all if statements in the script seem to be returning false. I have verified that both the array element and the input value are stri ...

The background gently fades away, directing all attention to the popup form/element

After extensive searching, I have yet to find a straightforward solution that seems to be a standard practice on the web. My goal is to create a form that appears in the center of the screen when a button is clicked using CSS or jQuery. I would like the ...

JavaScript: table is not defined

When creating a table using Django models and JavaScript, I encountered an issue where the cells values of the table could not be accessed from another JavaScript function. The error message indicated that the table was "undefined". Below is the HTML code ...

Send the JSON output to the controller function

Hello there! I am new to asp.net mvc and I'm looking for a way to pass JSonResult data to a controller method. In my View, I have set up a table like this: <table id="tbl_orderItems" class="table table-striped table-bordered table-hover dt-respo ...

Insert a fresh row into the current table

Is it possible to add a new row to an existing table in SAP UI5? Below is the code snippet: onInit: function() { var oModel = new sap.ui.model.json.JSONModel("Model/Clothing.json"); this.getView().setModel(oModel); var table = this.getView(). ...

Angular 2 is encountering issues with reading and displaying unicode characters (ud83dude31 or u0C28u0C3E) from the http response onto the user

My current task involves extracting unicode data from an http response, specifically for emojis. The response is in the form of a property-value pair within an object, with the message content being presented as JSON data ("messageContent":"hello \&bs ...

deactivating image mapping on mobile media screens

I'm looking to disable my image map on mobile screens using media queries. I've attempted to include some javascript in the head of my html file, but I encountered an error: <script src="http://code.jquery.com/jquery-1.11.3.min.js"></s ...

Troubleshooting an Angular application in Intellij using Chrome on a Windows operating system

I've been searching for a long time for a way to debug an Angular app in IntelliJ using Chrome on Windows. So far, I have not been successful in attaching a debugger to Chrome. I have tried launching Chrome with --remote-debugging-port=9222 and numer ...