使用Firebase v9调用doc、setDoc后Firestore未新增数据求助
排查Firestore数据写入失败的问题
核心问题:异步操作未正确处理
你的代码中createUserWithEmailAndPassword是异步函数,但未等待它执行完成就直接调用setDoc,会引发两个关键问题:
- 用户创建流程尚未完成时,Firestore权限规则可能阻止未完全认证的请求写入数据
- 异步操作的错误未被捕获,导致控制台无报错输出
修复代码(添加异步/await与错误捕获)
将signUp改为异步函数,等待用户创建完成后再执行Firestore写入操作,同时用try/catch捕获所有错误:
import { setDoc, doc } from "firebase/firestore"; import { createUserWithEmailAndPassword } from "firebase/auth"; async function signUp(email, password) { try { // 等待用户创建流程完成 const userCredential = await createUserWithEmailAndPassword(auth, email, password); // 优先使用用户UID作为文档ID(比email更可靠,避免特殊字符冲突) const userId = userCredential.user.uid; await setDoc(doc(db, "users", userId), { savedShows: [], }); console.log("数据写入成功"); } catch (error) { console.error("错误详情:", error); } }
其他排查方向
- Firestore权限规则检查:确认权限规则允许认证用户写入
users集合,推荐使用如下规则(确保只有当前用户能读写自己的文档):rules_version = '2'; service cloud.firestore { match /databases/{database}/documents { match /users/{userId} { allow read, write: if request.auth != null && request.auth.uid == userId; } } } - 文档ID合法性:若坚持使用email作为文档ID,需注意
@、.等特殊字符会被Firestore自动转义,但用户UID是更安全的选择 - Firebase初始化验证:确认
db和auth实例已正确初始化,env文件中的API_KEY、AUTH_DOMAIN等配置项已正常加载 - 控制台状态确认:在Firebase控制台的
Authentication页面查看是否有新用户创建,验证注册流程是否真的完成
内容的提问来源于stack exchange,提问作者Fatima
相关产品推荐
相关产品推荐

