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

Firebase获取登录用户邮箱报错及db.collection异常求助

解决方案

错误1:Cannot read properties of null (reading 'email')

直接读取auth.currentUser会返回null,因为页面加载时Firebase Auth还没完成用户状态同步。必须通过监听认证状态变化来确保用户登录后再执行后续操作,而非同步读取currentUser。

错误2:db.collection is not a function

Firebase v9+采用模块化API,不再支持db.collection()这种旧写法,要改用collection(db, "集合名")的方式调用。同时要确保db是通过getFirestore()正确初始化的实例。

修正后的代码

import { getAuth, onAuthStateChanged } from "firebase/auth";
import { getFirestore, collection, query, where, getDocs } from "firebase/firestore";

const auth = getAuth();
const db = getFirestore(); // 确保正确初始化Firestore实例

// 监听用户认证状态变化
onAuthStateChanged(auth, (user) => {
  if (user) {
    const userEmail = user.email;
    let clubName;

    // 使用模块化API查询users集合
    getDocs(query(collection(db, "users"), where("email", "==", userEmail)))
      .then((querySnapshot) => {
        querySnapshot.forEach((doc) => {
          console.log(doc.id, " => ", doc.data());
          const data = doc.data();
          clubName = data.name;
          
          // 必须在异步查询完成后再处理依赖clubName的逻辑
          const q = query(collection(db, "requests"), where("SendTo", "==", clubName));
          console.log("THE DATA YOU ARE LOOKING FOR: " + clubName);
          // 这里可以继续处理请求集合的逻辑,比如获取数据或监听变化
        });
      })
      .catch((error) => {
        console.log("Error getting documents: ", error);
      });
  } else {
    // 处理用户未登录的情况
    console.log("用户未登录");
  }
});

重要提示

  • 原代码中console.log(clubName)和const q = query(...)会在Firestore查询完成前执行,此时clubName还是undefined,必须把这些逻辑放到then回调内部,保证数据加载完成后再执行。
  • 确认你的项目使用Firebase v9+模块化SDK,所有Firestore操作都要使用对应的模块化方法,不要混用旧版命名空间API。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 06:50:27