我正在使用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);
}
我的代码有什么错?
1条答案
按热度按时间yrdbyhpb1#
因为你有
import { collection, getDocs,doc, getDoc, ,query}
,你没有导入where
-这解释了为什么编译器找不到它。为了能够使用
where
,请将其添加到Firestore的import
语句中:另请参阅有关运行简单和复杂查询的Firebase文档,该文档通常在其代码片段中显示必要的导入。