Firebase v9调用collection.get()报is not a function错误求助
问题原因
你使用的是Firebase 9+的模块化SDK,该版本放弃了旧版面向对象的链式调用设计,collection()函数仅用于生成集合引用对象,本身不携带get()方法,所有数据操作都需要调用单独导入的对应函数完成。
修复步骤
- 先从
firebase-firestore.js中导入获取集合文档的getDocs函数 - 将原有的链式调用写法替换为把集合引用传入
getDocs函数的写法
修正后完整代码
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.0.2/firebase-app.js"; import { getAuth, createUserWithEmailAndPassword, signOut, signInWithEmailAndPassword, onAuthStateChanged } from "https://www.gstatic.com/firebasejs/9.0.2/firebase-auth.js"; // 新增导入getDocs import { getFirestore, collection, getDocs } from "https://www.gstatic.com/firebasejs/9.0.2/firebase-firestore.js"; const firebaseConfig = { apiKey: "AIzaSyC3GLIN5TBmCDoTfy0dEOgOdvVvqNw-ric", authDomain: "auth-project-38aaa.firebaseapp.com", projectId: "auth-project-38aaa", storageBucket: "auth-project-38aaa.appspot.com", messagingSenderId: "431888894254", appId: "1:431888894254:web:71bb9b250fbb8a21edd2bf", measurementId: "G-6BBPCJ3814" }; const app = initializeApp(firebaseConfig); const auth = getAuth(app); const db = getFirestore(app); // get data 修正写法 const guidesCol = collection(db, 'guides'); getDocs(guidesCol).then(snapshot => { console.log(snapshot.docs); });
补充说明
如果后续需要查询单个文档,对应导入doc和getDoc函数即可,写法和查询集合逻辑一致。
内容的提问来源于stack exchange,提问作者Donn Deparsio
相关产品推荐
相关产品推荐

