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

Firebase身份验证后如何使用相同UID在Firestore中新增用户文档

问题修复方案

你代码的核心错误是用户uid的取值路径错误:createUserWithEmailAndPassword 方法返回的凭证对象 cred 中,用户唯一标识uid并不在cred根层级,而是存放在cred.user属性下。你传入doc()的cred.uid实际为undefined,Firestore的doc()方法收到undefined参数时会自动生成随机文档ID,因此出现文档ID与预期uid不一致的问题。

修复后完整代码

const handleSignup = ()=>{
    auth()
    .createUserWithEmailAndPassword(email, password)
    .then((cred) => {
        console.log(cred);
        // 修正uid取值路径
        const userId = cred.user.uid
        firestore()
        .collection('users')
        .doc(userId)
        .set({
          display_name:username
        })
        .then(() => {
          console.log('User added!');
        })
        // 补充Firestore写入错误捕获,方便排查问题
        .catch(firestoreErr => {
          console.error('用户信息写入失败:', firestoreErr)
        })
    })
    .catch(error => {
        console.log(error.code);
        if (error.code === 'auth/user-not-found') {
          console.error('Invalid Email or password');
        }else
          console.error('Sorry an error occured');
    });
  };

额外优化建议

  • 可以在取uid前先判断cred.user是否存在,避免极端场景下的空值报错
  • 可以将嵌套的Promise链扁平化,降低代码维护成本

内容的提问来源于stack exchange,提问作者Satyaki Das

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 19:39:02