Firestore报错TypeError: firestore.collection is not a function求解决方案
解决Firebase报错TypeError: firestore.collection is not a function
这个错误是因为你用了Firebase v9+的模块化SDK,但写法还停留在旧版的链式调用(v8及之前的写法)。v9+已经改成函数式调用方式,不能再通过firestore.collection()这种原型方法访问集合。
修正步骤:
- 你已经导入了
collection、doc、updateDoc这些模块化函数,直接用它们替代链式调用即可。 - 确保
firebaseConfig.js里正确导出了初始化后的Firebase App实例。
修改后的handleDateChange函数代码:
const handleDateChange = (date) => { console.log("Selected date:", date); setFormData({ ...formData, dob: date }); // 初始化Firestore实例 const db = getFirestore(firebaseApp); // 用模块化函数构建文档引用 const userDocRef = doc(collection(db, "users"), "dob"); // 执行更新操作 updateDoc(userDocRef, { dob: formatDOB(date) }) .then(() => { console.log("出生日期已成功保存到Firestore!"); }) .catch((error) => { console.error("保存出生日期到Firestore失败:", error); }); };
额外注意:
- 如果你要创建新文档而非更新已有文档,应该用
addDoc(collection(db, "users"), { dob: formatDOB(date) })。 - 当前用的文档ID是"dob",这更像字段名而非用户文档ID,建议替换成实际的用户唯一标识(比如用户UID),否则会持续覆盖同一个文档的数据。
- 检查
firebaseConfig.js的导出是否正确,示例如下:
// firebaseConfig.js import { initializeApp } from "firebase/app"; const firebaseConfig = { // 你的Firebase配置信息 }; const firebaseApp = initializeApp(firebaseConfig); export default firebaseApp;
内容的提问来源于stack exchange,提问作者Sricharan Ponna
相关产品推荐
相关产品推荐

