在集合中添加新文档后如何自动添加子集合?

问题描述 投票:0回答:1

我正在使用 angular@fire addDoc 将新文档添加到集合中。我想在将新文档添加到集合后自动添加子集合。基本上我必须获取添加的新文档的 id

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, []);
  }

我搜索的所有答案都至少有 5 岁了

angular ionic-framework angularfire
1个回答
0
投票

使用键盘公司的评论,这是有效的解决方案

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: []
    });
  });
© www.soinside.com 2019 - 2024. All rights reserved.