昨天既然寫入,今天就要想辦法拿出來~
getDocs()
獲取 collection 中的所有文件import { collection, getDocs } from "firebase/firestore";
async function fetchAndAddMarkers() {
const userLocationsCollection = collection(db, "userLocations");
const userLocationsSnapshot = await getDocs(userLocationsCollection);
userLocationsSnapshot.forEach((doc) => {
console.log(doc.id, " => ", doc.data());
});
}
where()
條件性的過濾獲取的資料import { collection, query, where, getDocs } from "firebase/firestore";
const q = query(collection(db, "userLocations"), where("online", "==", true));
const querySnapshot = await getDocs(q);
querySnapshot.forEach((doc) => {
console.log(doc.id, " => ", doc.data());
});
onSnapshot()
監聽資料使用 onSnapshot()
會持續監聽資料庫的某集合或文件是否發生變化,若發生變化會通知應用,設置後就會持續監聽直到銷毀為止。
const q = query(collection(db, "userLocations"));
const unsubscribe = onSnapshot(q, (querySnapshot) => {
const locations = [];
querySnapshot.forEach((doc) => {
const data = doc.data();
locations.push({ lat: data.lat, lng: data.lng });
console.log("locations :", locations);
});
一樣可以搭配 where()
來過濾監聽資料的範圍
const q = query(collection(db, "userLocations"), where("online", "==", true));
const unsubscribe = onSnapshot(q, (querySnapshot) => {
const locations = [];
querySnapshot.forEach((doc) => {
const data = doc.data();
locations.push({ lat: data.lat, lng: data.lng });
console.log("locations :", locations);
});