You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Firestore指定ID存文档报错:集合引用需奇数段数

问题解决:Firestore指定文档ID为用户UID时的路径错误

错误原因

你用addDoc(collection(db, "Support Network Member Accounts", ID))的写法有误——collection()函数传三个参数时,是用来定义子集合路径的(格式为父集合名/父文档ID/子集合名,路径段数必须是奇数),但你传的是集合名+文档ID,路径段数为2(偶数),因此触发了Invalid collection reference错误。

另外,addDoc本身是Firestore用于自动生成文档ID的方法,若要指定自定义ID,需搭配setDoc和doc()方法来创建文档引用。

修正后的代码

把原代码中的文档创建部分替换为以下内容:

createUserWithEmailAndPassword(auth, email, password)
  .then(async (cred) => {
    console.log(cred.user.uid);
    const ID = cred.user.uid;
    console.log("Account has been created with user ID:", ID);

    // 核心修改:用doc()指定自定义ID的文档引用,再用setDoc写入数据
    await setDoc(doc(db, "Support Network Member Accounts", ID), {
      firstName: firstName,
      surname: surname,
      contactNo: contactNo,
      email: email,
      password: password,
      confirmPassword: confirmPassword,
      dementiaRelation: dementiaRelation,
      dementiaHubUserID: dementiaHubUserID
    });

    console.log('Support Network Member Account Added Successfully!');
    alert('Account Created Successfully');
    navigation.replace('Login Page');
  })
  .catch(error => {
    console.log(error.message);
    alert(error.code);
    if (error.code === 'auth/user-not-found') {
      console.error('Invalid Email or password');
    } else {
      console.error('Sorry an error occured');
    }
  });

关键修改说明

  • 替换addDoc(collection(...))为setDoc(doc(db, "集合名", 自定义ID), 数据):
    • doc(db, "Support Network Member Accounts", ID):创建指向目标集合下、ID为用户UID的文档引用
    • setDoc():将数据写入该文档,文档不存在时自动创建;若需避免覆盖已有数据,可添加选项{ merge: true }
  • 简化了async/await与then的混用,让代码逻辑更清晰

内容的提问来源于stack exchange,提问作者Lauren Watters

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 16:17:32