Firebase文档引用错误排查:React Native项目字段增量失败
Firebase文档引用错误:Invalid document reference 解决方法
错误原因
你遇到的FirebaseError: Invalid document reference. Document references must have an even number of segments, but table/table1/recipe0 has 3错误,核心原因是Firebase的文档路径必须遵循「集合→文档→子集合→子文档」的交替结构,路径的总段数必须是偶数。你的路径table/table1/recipe0是3段,属于「集合→文档→文档」的非法结构,所以触发错误。
代码问题分析
你当前构建的文档路径table/${subcollectionName}/recipe${trocar}逻辑错误:
- 若
table是集合,table1是该集合下的文档,那么recipe0不能直接作为下一段(文档必须嵌套在集合下,不能直接嵌套在文档下) - 要么
recipe0是table1文档内的字段,要么recipe0是table1文档下子集合里的文档
解决方案
根据你的实际数据结构选择以下两种修改方式:
方式1:recipe[trocar]是tableN文档内的字段
如果你的数据结构是table集合下存储table1、table2等文档,每个文档内直接包含recipe0、recipe1等字段,修改代码如下:
const incrementRecipeTab = async (trocar, selectedTable) => { try { // 直接引用table集合下的tableN文档 const tableDocRef = doc(db, 'table', `table${selectedTable}`); const tableDocSnapshot = await getDoc(tableDocRef); if (tableDocSnapshot.exists()) { await updateDoc(tableDocRef, { [`recipe${trocar}`]: increment(1) }); console.log(`Recipe ${trocar} incremented successfully for table ${selectedTable}`); } else { console.error(`Table document ${selectedTable} does not exist`); } } catch (ex) { console.error('Error incrementing recipe:', ex); } };
方式2:recipe[trocar]是子集合中的文档
如果你的数据结构是table集合下的tableN文档,包含recipes子集合,子集合内有recipe0、recipe1等文档,修改代码如下:
const incrementRecipeTab = async (trocar, selectedTable) => { try { // 路径结构:集合table → 文档tableN → 子集合recipes → 文档recipeM const recipeDocRef = doc(db, 'table', `table${selectedTable}`, 'recipes', `recipe${trocar}`); const recipeDocSnapshot = await getDoc(recipeDocRef); if (recipeDocSnapshot.exists()) { // 替换`count`为你实际需要增量的字段名 await updateDoc(recipeDocRef, { count: increment(1) }); console.log(`Recipe ${trocar} incremented successfully for table ${selectedTable}`); } else { console.error(`Recipe document ${trocar} does not exist for table ${selectedTable}`); } } catch (ex) { console.error('Error incrementing recipe:', ex); } };
关键说明
- Firebase文档引用的每一段必须交替为「集合名/文档ID」,所以总段数一定是偶数
- 先确认你的Firebase数据库结构,确保路径和实际数据结构完全匹配
内容的提问来源于stack exchange,提问作者DanielRM
相关产品推荐
相关产品推荐

