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

React集成Firebase9调用db.collection提示is not a function问题求助

问题原因

Firebase v9 采用模块化API设计,移除了旧版本中db实例上挂载的collection、doc等链式调用方法,所有操作都需要通过从firebase/firestore导入的顶级函数完成。你当前代码中仍然使用v8及更早版本的db.collection()链式写法,没有用到已导入的collection、doc方法,所以会同时出现导入灰显和运行时报错的问题。

解决方案

方案1:使用标准模块化API(官方推荐)

修改databaseservice.js代码,替换为v9的函数式写法即可,注意新增导入getDoc方法:

import { db } from './config';
import { doc, getDoc } from 'firebase/firestore';

export const getChapters = (scanId) => {
    // 构造文档引用
    const docRef = doc(db, 'somecollection', scanId);
    // 读取文档
    getDoc(docRef)
        .then((docSnap) => {
            if (docSnap.exists()) {
                console.log('Document data:', docSnap.data());
            } else {
                console.log('No such document!');
            }
        })
        .catch((error) => {
            console.log('Error getting document:', error);
        });
};

方案2:正确使用compat版本兼容旧写法

如果要保留原有链式调用写法,需要确保所有Firebase相关导入都使用compat路径,不要混用标准模块化版本和compat版本,之前compat版本报错基本都是导入路径混用导致的:

  1. 修改config.js代码:
import firebase from 'firebase/compat/app';
import 'firebase/compat/firestore';

const firebaseConfig = {
    apiKey: '****',    
    authDomain: '*****',    
    projectId: '*****',    
    storageBucket: '*****',    
    messagingSenderId: '****',    
    appId: '*****',
};

const app = firebase.initializeApp(firebaseConfig);
export const db = app.firestore();
  1. 原有databaseservice.js中的db.collection()链式写法可直接正常使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 17:24:02