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

React接入Firestore报错:db.collection不是函数,求解决方法

解决Firestore TypeError: db.collection is not a function错误

你的问题出在Firebase v9+采用了模块化API,不再支持旧版的db.collection()链式调用写法,需要改用配套的模块化函数来操作数据库。

修正步骤:

  1. 从firebase/firestore导入collection和getDocs两个核心函数
  2. 替换原有的数据获取逻辑,使用模块化函数替代链式调用

修改后的完整代码:

firebase.js

import { initializeApp } from 'firebase/app';
import { getFirestore, collection, getDocs } from 'firebase/firestore';

var firebaseConfig = {
  apiKey: 'xx',
  authDomain: 'xx',
  projectId: 'xx',
  storageBucket: 'xx',
  messagingSenderId: 'xx',
  appId: 'xx',
  measurementId: 'G-xxxx',
};

// Initialize Firebase
var app = initializeApp(firebaseConfig);
export const db = getFirestore(app);

// 修正后的数据获取逻辑
try {
  console.log("recupero lista news_profiles");
  // 使用collection和getDocs替代原链式调用
  getDocs(collection(db, 'news_profiles'))
    .then((querySnapshot) => {
      console.log(querySnapshot);
      const data = [];
      querySnapshot.forEach((doc) => {
        console.log(doc.id, ' => ', doc.data());
        data.push(doc.data());
      });
      console.log(data);
    })
    .catch((error) => {
      console.log('Error getting documents: ', error);
    });
} catch (error) {
  console.log('Error: ' + error);
}

关键说明:

  • Firebase v9+为了优化打包体积,采用了树摇友好的模块化设计,所有数据库操作都需要通过单独导入的函数完成,不再支持db.collection()这种面向对象的链式调用
  • collection(db, '集合名')用于创建集合引用,getDocs(集合引用)用于获取集合下的所有文档快照

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 03:41:32