Firestore中检查指定文档是否存在?调用get()遇TypeError报错
问题分析与解决方案
错误TypeError: userRef.get is not a function的核心原因是你使用了Firestore v9模块化SDK,但写法沿用了v8命名空间风格的API。在v9中,获取文档快照需要调用独立的getDoc()函数,而不是直接在DocumentReference对象上调用.get()方法。
修正后的代码
import { doc, getDoc, setDoc } from "firebase/firestore"; // 确保导入getDoc // ...其他代码 const userRef = doc(db, 'user', user.uid); const snapshot = await getDoc(userRef); // 改用getDoc函数获取快照 const {email} = user; const {displayName} = data; if(!snapshot.exists()) { // v9中判断文档存在需调用exists()方法 await setDoc(userRef, { // 直接复用已创建的userRef,无需重复调用doc() displayName, email, createdAt: new Date() }) }
关键修改点
- 导入
getDoc函数:必须从firebase/firestore中导入该方法才能使用 - 替换
userRef.get()为getDoc(userRef):v9模块化SDK将操作拆分为独立函数,不再挂载在引用对象上 - 替换
snapshot.exists为snapshot.exists():v9中判断文档是否存在是调用方法,而非访问属性 - 复用
userRef:创建文档时直接使用已定义的引用,避免重复生成相同对象
内容的提问来源于stack exchange,提问作者lampshed
相关产品推荐
相关产品推荐

