React firebase错误:where'未定义查询调用firebase in react

cvxl0en2  于 2023-10-22  发布在  React
关注(0)|答案(1)|浏览(153)

我正在使用React与Firebase。但是当我在查询中使用where条件时,它显示错误:

'where' is not defined

1.我有一个名为comapntList的集合,我已经提交了以下文件:

id“2”name“ABC”

1.这是我的firebase规则权限

rules_version = '2';
 service cloud.firestore {
   match /databases/{database}/documents {
     match /{document=**} {
       allow read, write;
     }
   }
 }

下面是firebase的配置:

import { initializeApp } from "firebase/app";
    import { getAuth } from "firebase/auth";
    import { getFirestore } from "firebase/firestore";
    import { getStorage } from "firebase/storage";
    const firebase = {
      apiKey: "xx",
      authDomain: "xx",
      projectId: "xx",
      storageBucket: "xx",
      messagingSenderId: "x",
      appId: "xx",
      measurementId: "G-J7CJWNMETH"

    };

    const firebaseApp  = initializeApp(firebase);
     const db = getFirestore(firebaseApp)
     const storage = getStorage(firebaseApp);
    const auth = getAuth();
     
    export { firebaseApp , auth,db,storage };

1.代码如下:

const collection_ref = collection(db, "comapntList")
       const q = query(collection_ref, where("id", "==", "2"))

       const querySnapshot = await getDocs(q);

       if (querySnapshot.size === 1) {
         querySnapshot.forEach((doc) => {

         console.log(doc.data());
         });
       } else {
         console.log('Document not found or multiple documents found.');
       }
     } catch (error) {
       console.error('Error fetching data:', error);
     }

我的代码有什么错?

yrdbyhpb

yrdbyhpb1#

因为你有import { collection, getDocs,doc, getDoc, ,query},你没有导入where-这解释了为什么编译器找不到它。
为了能够使用where,请将其添加到Firestore的import语句中:

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

另请参阅有关运行简单和复杂查询的Firebase文档,该文档通常在其代码片段中显示必要的导入。

相关问题