Firebase创建子集合遇错误,如何生成随机Hash文档ID?
Firestore集合层级创建报错及解决办法
需求说明
要创建的Firestore集合结构为:all_delivery > 哈希ID(变量this.delivery_client_hashid) > this_client_delivery > 随机哈希ID的文档
问题代码
const get_id2 = firebase.firestore().collection('all_delivery').doc(this.delivery_client_hashid).collection("this_client_delivery").doc();
报错信息
FirebaseError: Invalid document reference. Document references must have an even number of segments, but all_delivery/5BcX5Mf6TujUiOSk6eup/this_client_delivery has 3.
报错原因
Firestore对引用类型有严格规则:
- 文档引用的路径必须是偶数段(格式为
集合/文档/集合/文档交替,比如all_delivery/xxx/this_client_delivery/yyy是4段,属于合法文档引用) - 集合引用的路径是奇数段(比如报错里的
all_delivery/xxx/this_client_delivery是3段,属于集合引用)
你遇到的报错,是因为代码中某个地方把this_client_delivery这个集合引用当成了文档引用使用(比如用它执行文档级别的操作),而不是你写的那段带.doc()的代码本身有问题——你的代码生成的是合法的4段文档引用。
正确实现方法
你写的生成随机哈希ID文档的代码本身是正确的,只需确保后续操作使用的是带.doc()的文档引用即可。示例如下:
// 生成带随机ID的文档引用 const deliveryDocRef = firebase.firestore() .collection('all_delivery') .doc(this.delivery_client_hashid) .collection("this_client_delivery") .doc(); // 获取自动生成的随机哈希ID const randomDocId = deliveryDocRef.id; // 向该文档写入数据(示例) deliveryDocRef.set({ createTime: new Date(), // 其他业务字段 }) .then(() => { console.log(`文档已创建,ID: ${randomDocId}`); }) .catch(err => { console.error('创建文档失败:', err); });
内容的提问来源于stack exchange,提问作者ZION WONG
相关产品推荐
相关产品推荐

