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

Flutter Firestore中如何获取当前用户自动生成文档ID?登录后获错ID求助

登录后获取用户文档ID不符的解决办法

从你提供的截图(Firebase相关代码界面)来看,常见的问题和修复方案如下:

  • 别把Auth UID和文档ID搞混
    很多人会误把Firebase Auth的用户UID当成Firestore的文档ID,但如果创建用户文档时是让系统自动生成ID(没用Auth UID作为文档ID),那两者肯定不一样。要是需要关联,创建文档时直接用当前用户的Auth UID作为文档ID:

    // 创建用户文档时绑定Auth UID
    const userDocRef = db.collection('users').doc(firebase.auth().currentUser.uid);
    await userDocRef.set({ name: 'xxx', email: 'xxx@xxx.com' });
    
  • 查询条件要精准
    如果是通过查询获取用户文档,必须用当前用户的唯一标识(比如邮箱、Auth UID)作为查询条件,再从结果里拿文档ID:

    // 按当前用户邮箱查询文档并获取ID
    const querySnapshot = await db.collection('users')
      .where('email', '==', firebase.auth().currentUser.email)
      .get();
    if (!querySnapshot.empty) {
      querySnapshot.forEach(doc => {
        console.log('正确的文档ID:', doc.id);
      });
    }
    
  • 确保登录完成后再查文档
    一定要等登录状态稳定后再执行文档查询,把获取逻辑放在onAuthStateChanged回调里,避免还没拿到当前用户就跑查询:

    firebase.auth().onAuthStateChanged(currentUser => {
      if (currentUser) {
        // 登录成功后再查文档
        db.collection('users').where('uid', '==', currentUser.uid).get()
          .then(snapshot => {
            snapshot.forEach(doc => console.log('目标文档ID:', doc.id));
          });
      }
    });
    

内容的提问来源于stack exchange,提问作者Syed Rehan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 19:57:38