How do I add sub collection automatically after adding a new document to a collection?

32 Views Asked by At

I am adding a new document to a collection with angular@fire addDoc. I want to add a sub-collection automatically after adding a new document to a collection. basically I have to get the id of the new doc added

ts

  addTask(task: Task) { 
    collectionRef = collection(this.firestore, 'tasks');
    addDoc(collectionRef, { 
      ...task, 
      user: this.auth.currentUser?.uid 
    });
    
   // I want to get the id of the new document I have added to that collectionRef
    const id = "Get from new addDoc"; 
    const photoSubCollection = collection(this.firestore, `tasks/${id}/photos-sub-collection`);
    const docRef =  addDoc(photoSubCollection, []);
  }

All answers I searched for are at least 5 years old

1

There are 1 best solutions below

0
Thomas Degroot On

Using Keyboard Corporation comment, this is the solution that worked

addTask(task: Task) { 
  addDoc(this.collectionRef, { 
    ...task, 
    user: this.auth.currentUser?.uid 
  }).then((docRef) => {
    const id = docRef.id;
    const userSubCollection = collection(this.firestore, `tasks/${id}/photos-sub-collection`);
    addDoc(userSubCollection, {
      photo: "photos",
      photolist: []
    });
  });
}