从Firebase Firestore获取集合父ID时遇TypeError错误求助
解决Firestore获取集合父ID时的「undefined is not an object」错误
错误原因
QuerySnapshot对象不存在parent属性,你错误地从查询快照中获取父引用,导致parentDoc为undefined- 根集合(如
"users")的父引用本身是null,直接访问id会触发类型错误 - 调用异步函数时未处理Promise,直接赋值得到的是Promise对象而非实际结果
修正方案
1. 直接从集合引用获取父ID
不需要调用getDocs,集合引用本身就带有parent属性,直接从collectionRef读取即可,同时要处理根集合的特殊情况:
修正后的getParentId函数:
import { getFirestore, collection } from "@firebase/firestore" // 确保db已初始化 const db = getFirestore(); export async function getParentId(collectionPath) { const collectionRef = collection(db, collectionPath); try { const parentRef = collectionRef.parent; // 根集合的parent为null,先判断再返回ID return parentRef ? parentRef.id : null; } catch (error) { console.error("Error getting parent ID:", error); return null; } }
2. 正确调用异步函数
getParentId是异步函数,调用时必须通过await(需在async函数内)或.then()处理结果:
方式一:使用await(在async函数中)
import { getParentId } from '../Firebase-Config' // 示例:在React组件的useEffect中调用 useEffect(() => { const fetchParentId = async () => { const parentId = await getParentId("users"); console.log('Parent ID:', parentId); }; fetchParentId(); }, []);
方式二:使用.then()
import { getParentId } from '../Firebase-Config' getParentId("users").then(parentId => { console.log('Parent ID:', parentId); });
额外说明
如果你的集合路径是嵌套结构(比如"users/abc123/posts"),collectionRef.parent会指向"users/abc123"这个文档引用,此时parentRef.id就是"abc123";如果是根集合(如"users"),parentRef为null,函数返回null,避免报错。
内容的提问来源于stack exchange,提问作者Mahmoud Hlal
相关产品推荐
相关产品推荐

