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

最新版Firebase删除Firestore文档报doc is not a function如何解决?

错误根因

  • 变量名冲突覆盖了官方导入的方法:你从firebase/firestore导入的doc是用于生成文档引用的工具函数,但你后续代码两次声明了同名变量,直接覆盖了原函数:
    1. 冗余代码const doc = getDocs(q);,这行本身没有实际作用还抢占了变量名
    2. 遍历查询结果时的回调参数也命名为doc
      调用doc(db, "history", doc.id)时实际触发的是你自定义的变量而非官方方法,因此抛出类型错误。
  • 额外语法问题:deleteGame方法未声明async,直接使用await会触发语法报错。

修复后代码

import { where, query, deleteDoc, collection, doc, getDocs, getFirestore } from "firebase/firestore";
    
async deleteGame(game)  {            
  const db = getFirestore();
  const q = query(collection(db, "history"), where("date", "==", game.date));
  const querySnapshot = await getDocs(q);

  querySnapshot.forEach((docItem) => {    
    deleteDoc(doc(db, "history", docItem.id));
  });
}

可选批量删除优化

如果匹配的文档数量较多,可使用批量写入接口减少请求次数:

import { where, query, writeBatch, collection, doc, getDocs, getFirestore } from "firebase/firestore";
    
async deleteGame(game)  {            
  const db = getFirestore();
  const batch = writeBatch(db);
  const q = query(collection(db, "history"), where("date", "==", game.date));
  const querySnapshot = await getDocs(q);

  querySnapshot.forEach((docItem) => {    
    batch.delete(doc(db, "history", docItem.id));
  });

  await batch.commit();
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 19:36:03