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>