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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 09:55:20