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

React组件使用Firestore报错:TypeError: db.collection is not a function

解决Firestore报错“TypeError: db.collection is not a function”

错误原因

你使用的是Firebase v9+的模块化API,但代码里仍沿用了Firebase v8的命名空间式调用语法(db.collection()),v9+已不再支持这种链式调用方式,必须使用独立的Firestore函数。

修正步骤及代码

  1. 导入Firestore所需的独立函数
    在组件文件顶部新增collection和addDoc的导入:
import { useAuth } from '@/firebase/AuthContext';
import { db } from '@/firebase/firebaseConfig';
import { collection, addDoc } from 'firebase/firestore'; // 新增导入
  1. 重写createDocument函数
    改用v9+的模块化API语法,同时注意Firestore要求存储的数据为键值对对象(不能直接传字符串):
async function createDocument(collectionName, data) {
  try {
    // 先创建集合引用,再添加文档
    const collectionRef = collection(db, collectionName);
    const docRef = await addDoc(collectionRef, { text: data });
    return docRef.id;
  } catch (error) {
    console.error('Error creating document:', error);
    throw error;
  }
}
  1. 修正异步函数调用
    createDocument是异步函数,调用时必须添加await并处理可能的错误,避免未捕获的Promise:
async function handleKeyPress(event) {
  if (event.key === 'Enter') {
    console.log(text);
    try {
      await createDocument('posts', text);
      console.log('document has been created in Firestore');
    } catch (err) {
      console.error('Failed to create document:', err);
    }
  }
}

额外说明

你的Firebase配置文件是正确的,getFirestore(app)已经正确初始化了Firestore实例,问题仅出在组件内的API调用方式上。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 20:04:52