首页 > 解决方案 > TypeError: _firebase_config__WEBPACK_IMPORTED_MODULE_1__.db.collection 不是函数 firebase

问题描述

出现错误的代码:

const user = db.collection("users").doc(`${match.params.id}`).get();

错误:

TypeError: _firebase_config__WEBPACK_IMPORTED_MODULE_1__.db.collection is not a function

这是firebase-config.js

 // Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getAnalytics } from "firebase/analytics";
import { getAuth } from "firebase/auth";
import { getFirestore } from "firebase/firestore";

const firebaseConfig = {
   apiKey: "xxxxxxxxxx",
   authDomain: "xxxxxxx.firebaseapp.com",
   projectId: "PROJECT-ID",
   storageBucket: "xxxxxxxxxx.appspot.com",
   messagingSenderId: "xxxxxxxxx",
   appId: "xxxxxxxxxxx",
   measurementId: "xxxxxxxxx",
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
const db = getFirestore(app);
const auth = getAuth(app);
export { analytics, auth, db };

尝试

重新安装 Firebase,Nopes 重新安装所有模块(删除 node_modules 文件夹和 npm install),Nopes

标签: reactjsfirebasegoogle-cloud-firestore

解决方案


对于 Firebase Modular 或9.0.0更高版本,您应该在查询中使用新的实现,例如

之前:版本 9compat或版本 8 及以下

import "firebase/compat/firestore"

const db = firebase.firestore();
db.collection("cities").where("capital", "==", true)
    .get()
    .then((querySnapshot) => {
        querySnapshot.forEach((doc) => {
            // doc.data() is never undefined for query doc snapshots
            console.log(doc.id, " => ", doc.data());
        });
    })
    .catch((error) => {
        console.log("Error getting documents: ", error);
    });

之后:版本 9 模块化

import { getFirestore, collection, query, where, getDocs } from "firebase/firestore";

const db = getFirestore(firebaseApp);

const q = query(collection(db, "cities"), where("capital", "==", true));

const querySnapshot = await getDocs(q);
querySnapshot.forEach((doc) => {
  // doc.data() is never undefined for query doc snapshots
  console.log(doc.id, " => ", doc.data());
});

在你的情况下,它应该是:

const docRef = doc(db, "users", `${match.params.id}`);
const user = await getDoc(docRef);

推荐阅读