无法向Firestore数据库添加数据,报Invalid collection reference错误
错误原因
你遇到的报错核心由两个问题共同触发:
Invalid collection reference. Collection references must have an odd number of segments, but profiles/undefined has 2
- 用户注册接口返回异常:
signUpNewUser执行后返回的user对象为空,导致user.uid取值为undefined,拼接出的路径profiles/undefined为无效路径
- 用户注册接口返回异常:
- Firestore API用法错误:
collection()方法用于获取集合引用,要求传入的路径段数必须为奇数(Firestore路径规则为「集合/文档/集合」交替,集合路径的段数永远是奇数),而你传入的profiles/${user.uid}是文档路径,段数为偶数,不符合collection()的入参要求。另外addDoc()是用于向集合新增自动生成ID的文档的API,如果你要指定文档ID为user.uid,不应该使用该组合。
- Firestore API用法错误:
修复代码
如果你是要向profiles集合中新增ID为当前用户UID的文档,修改为以下写法即可:
import { doc, setDoc } from "firebase/firestore"; const user = await signUpNewUser(auth, email, password); // 先校验用户信息是否正常返回 if (!user?.uid) { console.error('未获取到有效用户ID,请检查注册逻辑'); return; } // 指定要写入的文档路径,调用setDoc写入数据 const docRef = doc(db, 'profiles', user.uid); await setDoc(docRef, { nama: form.nama, createdAt: new Date().getTime().toString(), }); console.log("Document written with ID: ", docRef.id);
如果你确实是需要在profiles/{uid}文档下新增子集合的文档,需要补全子集合名称,比如要写入子集合posts的话,写法如下:
import { collection, addDoc } from "firebase/firestore"; const user = await signUpNewUser(auth, email, password); if (!user?.uid) { console.error('未获取到有效用户ID,请检查注册逻辑'); return; } // 3段路径,符合集合路径的奇数段要求 const colRef = collection(db, 'profiles', user.uid, 'posts'); const docRef = await addDoc(colRef, { title: '示例标题', content: '示例内容' })
内容的提问来源于stack exchange,提问作者Aswad Zainil Mibat
相关产品推荐
相关产品推荐

