Reputation: 81
I have a problem with angular firebase solution.
What I'm trying to do is to add a property to already existing in firestore document.
I have the user interface that looks like this
export interface User {
email: string;
uid: string;
photoURL?: string;
displayName?: string;
teams?: string[];
}
I want to create a team and add that team id to teams
array in the existing User object.
I don't want to get all user data, but just put a new value to that field.
Is that possible? Maybe you have some suggestions on how to do that more efficient?
The team interface looks like that
export interface Team {
name: string;
description?: string;
admin?: string; // = creator - first user
members?: string[]; // array of users UIDs.
boards?: string[]; // array of board docs id.
}
The component responsible for adding a team is just a form so `onSubmit()' I've tried doing the following but I have no idea how to put that team document id to the user object.
onSubmit(form: NgForm) {
const newTeam: Team = {
name: form.value.name,
description: form.value.description,
admin: this.auth.currentUserId,
members: [this.auth.currentUserId],
};
const userRef: AngularFirestoreDocument<any> = this.afs.doc(
`users/${this.auth.currentUserId}`
);
let teamRefId = '';
this.afs.collection('teams').add(newTeam).then((docRef) => teamRefId = docRef.id);
this.router.navigateByUrl('/dash');
}
Any ideas? Maybe that should be some kind of spread operator but once again I don't want to get user object and post it back to firestore but just update that one field...
Upvotes: 1
Views: 2868
Reputation: 3740
You can do this by updating the doc with the following:
let teamArray = []; // if not excisting.
teamArray.push(teamRefId); // or just add it if it's.
userRef.update({teams: teamArray});
An update will not change the anything else except the team. If the team not excist the team will be added.
Upvotes: 1