React接入Firestore报错:db.collection不是函数,求解决方法
解决Firestore TypeError: db.collection is not a function错误
你的问题出在Firebase v9+采用了模块化API,不再支持旧版的db.collection()链式调用写法,需要改用配套的模块化函数来操作数据库。
修正步骤:
- 从
firebase/firestore导入collection和getDocs两个核心函数 - 替换原有的数据获取逻辑,使用模块化函数替代链式调用
修改后的完整代码:
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
相关产品推荐
相关产品推荐

