最新版Firebase删除Firestore文档报doc is not a function如何解决?
错误根因
- 变量名冲突覆盖了官方导入的方法:你从
firebase/firestore导入的doc是用于生成文档引用的工具函数,但你后续代码两次声明了同名变量,直接覆盖了原函数:- 冗余代码
const doc = getDocs(q);,这行本身没有实际作用还抢占了变量名 - 遍历查询结果时的回调参数也命名为
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
相关产品推荐
相关产品推荐

