Firebase使用Google SignIn时Firestore用户重复及用户存储方案问询
问题1:当前用户关联数据存储方案是否最高效?
不是最优方案,存在两个核心问题:
- 用
addDoc自动生成文档ID,没有和Firebase Auth返回的全局唯一用户标识uid绑定,后续查询指定用户的关联数据时,需要通过邮箱等字段做集合过滤查询,性能远低于直接按文档ID精确查询 - 缺少唯一标识约束,容易产生重复的用户数据记录
最优实现逻辑是直接使用用户的uid作为Firestore中users集合的文档ID,后续读写用户数据都通过uid定位文档,不需要额外字段过滤,查询效率最高。
问题2:如何解决Google登录重复生成用户记录的问题?
重复记录的根因是你在每次Google登录成功后都无条件调用addDoc新增文档,没有判断当前用户是否已经在Firestore中存储过数据。修正方案如下:
- 统一邮箱注册、Google登录的用户数据存储逻辑,都用
uid作为文档ID - 登录/注册流程中,先判断对应用户
uid的文档是否存在,仅不存在时才写入初始数据,已存在则跳过写入或按需更新字段
修正后的邮箱注册代码
import { getAuth, createUserWithEmailAndPassword } from "firebase/auth"; import { getFirestore, doc, setDoc } from "firebase/firestore"; // ... signUp() { const auth = getAuth(); const db = getFirestore(); createUserWithEmailAndPassword( auth, this.createEmail, this.createPassword ).then(async (userCredential) => { const user = userCredential.user; // 用uid作为文档ID写入用户数据 await setDoc(doc(db, "users", user.uid), { email: this.createEmail, name: this.createName, }); this.$router.push("/"); }); },
修正后的Google登录代码
import { getAuth, signInWithPopup, GoogleAuthProvider } from "firebase/auth"; import { getFirestore, doc, getDoc, setDoc } from "firebase/firestore"; // ... googleSignIn() { const auth = getAuth(); const provider = new GoogleAuthProvider(); const db = getFirestore(); signInWithPopup(auth, provider) .then(async (result) => { const user = result.user; const userDocRef = doc(db, "users", user.uid); const userDocSnap = await getDoc(userDocRef); // 仅用户文档不存在时写入初始数据 if (!userDocSnap.exists()) { await setDoc(userDocRef, { email: user.email, name: user.displayName, }); } this.$router.push("/"); }) },
额外优化建议
可以搭配Firestore安全规则限制用户仅能操作自己的文档,提升数据安全性:
rules_version = '2'; service cloud.firestore { match /databases/{database}/documents { match /users/{userId} { allow read, write: if request.auth != null && request.auth.uid == userId; } } }
内容的提问来源于stack exchange,提问作者ARNON
相关产品推荐
相关产品推荐

