ReactNative中使用Firebase新语法为文档添加集合遇错求助
Firebase v9+ 在文档下创建子集合的正确写法
错误原因解析
你碰到的FirebaseError: [code=invalid-argument]: Invalid collection reference. Collection references must have an odd number of segments, but chats/RXoMunEWYes4mu0HdFHq has 2错误,核心问题是:
chats/{id}是文档路径(两段,偶数),但你用了collection()方法去创建引用,而集合引用要求路径段数必须是奇数(比如chats是1段,chats/{id}/messages是3段)。- 正确获取文档引用应该用
doc()方法,而非collection()。
修正后的代码
写法1:使用async/await(推荐,代码更简洁)
const docRef = doc(fireStore, "chats", id); try { const newDocRef = await addDoc(collection(docRef, "messages"), { timestamp: firebase.firestore.FieldValue.serverTimestamp(), message: userInput, displayName: auth.currentUser.email, photoURL: auth.currentUser.photoURL, }); console.log("New Id: ", newDocRef.id); } catch (e) { console.log("Message creation error: ", e); }
写法2:使用then/catch
const docRef = doc(fireStore, "chats", id); addDoc(collection(docRef, "messages"), { timestamp: firebase.firestore.FieldValue.serverTimestamp(), message: userInput, displayName: auth.currentUser.email, photoURL: auth.currentUser.photoURL, }) .then((newDocRef) => { console.log("New Id: ", newDocRef.id); }) .catch((e) => { console.log("Message creation error: ", e); });
关键注意事项
- Firebase v9+模块化语法中:
- 获取文档引用:用
doc(数据库实例, 父集合名, 文档ID),路径段数为偶数 - 创建子集合引用:用
collection(文档引用, 子集合名),此时路径段数为奇数,符合集合引用的规则
- 获取文档引用:用
- 不要同时混用
await和then/catch,否则会导致Promise逻辑混乱(你原代码中await和then混用,会导致newDocRef在then中无法正确获取)
内容的提问来源于stack exchange,提问作者Collins Olix
相关产品推荐
相关产品推荐

