如何用AngularFire添加Firestore文档后自动创建子集合?
AngularFire 获取 addDoc 新增文档ID并创建子集合
你需要通过addDoc的返回值获取新文档ID,因为addDoc是异步方法,返回一个包含新增文档引用的Promise,从这个引用里就能拿到ID。以下是修正后的代码:
方法一:使用 async/await(推荐,代码更清晰)
async addTask(task: Task) { const collectionRef = collection(this.firestore, 'tasks'); // 等待文档添加完成,获取文档引用 const docRef = await addDoc(collectionRef, { ...task, user: this.auth.currentUser?.uid }); // 从文档引用中提取ID const taskId = docRef.id; // 创建子集合并添加初始文档(注意:Firestore文档必须是对象,不能直接传数组) const photoSubCollection = collection(this.firestore, `tasks/${taskId}/photos-sub-collection`); await addDoc(photoSubCollection, {}); }
方法二:使用 then 链式调用
如果不想用async/await,也可以通过Promise链式处理:
addTask(task: Task) { const collectionRef = collection(this.firestore, 'tasks'); addDoc(collectionRef, { ...task, user: this.auth.currentUser?.uid }) .then(docRef => { const taskId = docRef.id; const photoSubCollection = collection(this.firestore, `tasks/${taskId}/photos-sub-collection`); return addDoc(photoSubCollection, {}); }) .catch(error => { // 处理可能的错误 console.error('操作失败:', error); }); }
关键说明
addDoc执行成功后会返回DocumentReference对象,该对象的id属性就是新增文档的自动生成ID。- 必须等待
addDoc异步操作完成后再获取ID,否则会拿到未定义的值,所以要用await或then处理异步流程。 - Firestore文档要求是键值对结构,不要直接传入数组,示例中用空对象
{}作为子集合初始文档,你可以根据需求添加实际字段。
内容的提问来源于stack exchange,提问作者Thomas Degroot
相关产品推荐
相关产品推荐

