I am trying to learn firebase. I am making a project like Linkedin using Angular and Firebase.
I am using the @angular/fire package in my project.
So far I have done authentication and adding some basic info of a user. I have users collection where each documentId have information like name, email and etc
Now my next goal is to create a work experience section. Since a user can have multiple work experience.
I have to decided to proceed with sub-collection under each user document id instead of creating a separate collection for work-experience.
Now I am having a bit trouble how to add sub-collection in my users collection.
A user can only add/update one experience at a time. My UI will be something similar to Linkedin. When the 'Add Experience' button is clicked a modal will pop up and there will be a form inside the form with fields such as jobTitle, companyName and etc. So once the submit is clicked I want to save that data under the work-experience sub-collection with a unique documentId.
Currently I am adding my basic info like this
Adding
addUser(user: any): Observable<void> {
const ref = doc(this.firestore, 'users', user.uid);
return from(setDoc(ref, user));
}
Updating
updateUser(user: any): Observable<void> {
const ref = doc(this.firestore, 'users', user.uid);
return from(updateDoc(ref, { ...user }));
}
Now I want to add sub-collection called work-experience under the users collection.
CodePudding user response:
From your other question I think you need to add a sub-collection which contains a document with ID work-experience.
If my assumption is correct, do as follows to create the DocumentReference to this Document:
const workExperienceDocRef = doc(this.firestore, `users/${user.uid}/sub-sections/work-experience`);
Note: Make sure to use back ticks.
And then you can set the data of this doc as follows, for example:
return from(setDoc(workExperienceDocRef, {experiences: [{years: "2015-2018", company: "comp1"}, {years: "2018-2021", company: "comp2"}]}));
If you want to create a sub-collection for the user's document, do as follows:
const userSubCollection = collection(this.firestore, `users/${user.uid}/sub-collection`);
Then you can use the addDoc() method, which will automatically generate the document ID.:
const docRef = await addDoc(userSubCollection, {
foo: "bar",
bar: "foo"
});
