Problem:
I am using react with Firebase. But when I using where condition in query it show error:
'where' is not defined
-
I have collection named comapntList and I have filed below:
id “2”
name “ABC” -
Here is my firebase rule permission
rules_version = '2'; service cloud.firestore { match /databases/{database}/documents { match /{document=**} { allow read, write; } } }
Here is the firebase config:
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 };
-
Here is code:
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); }
what is the wrong of my code?
Solution:
Since you have import { collection, getDocs,doc, getDoc, ,query}
, you’re not importing where
– which explains why the compiler can’t find it.
To be able to use where
, add it to your import
statement for Firestore:
import { collection, getDocs,doc, getDoc, query, where } from "firebase/firestore";
Also see the Firebase documentation on running simple and complex queries, which usually shows the necessary imports in its code snippets.