I am trying to access the fields lat: "" and lng: "" that are saved inside a subcollection "userLocations" inside that userID document in the main collection "locations". Here is a screenshot of what it looks like.
As you can see I have a userID that saves lats and lngs.
I CAN access all lat, and lng of each document inside userLocation collection but for ONE USER ONLY if and only if I copy and paste that userID.
Here is the code that I used to access only one user's lat and lng:
useEffect(() => {
const fetch = async () => {
try {
const mainCollectionLocations = collection(db, "locations");
const userDocRef = doc(
mainCollectionLocations,
"LhCNVWJt5bdI0slgBPnbmESrwJh1" //PROBLEM I need to go through all documents available
);
const userLocationSubCollection = collection(
userDocRef,
"userLocation"
);
onSnapshot(userLocationSubCollection, (querySnapshot) => {
let loc = querySnapshot.docs.map((doc) => ({
lat: doc.data().lat,
lng: doc.data().lng,
}));
setLocations(loc);
});
} catch (error) {
console.log(error);
}
};
fetch();
}, []);
BUT I CANNOT iterate over EACH user getting each user's lat and lng. Here is the current code I'm using in order to try to accomplish this:
useEffect(() => {
const fetch = async () => {
try {
const mainCollectionLocations = collection(db, "locations");
const querySnapshot = await getDocs(mainCollectionLocations);
let allLocations = [];
querySnapshot.forEach(async (doc) => {
console.log("start for loop");
console.log("doc-ref:", doc.ref);
const userLocationSubCollection = collection(doc.ref, "userLocation");
console.log("userLocationSubCollection: ", userLocationSubCollection);
// const subQuerySnapshot = await getDocs(userLocationSubCollection);
onSnapshot(userLocationSubCollection, (querySnapshot) => {
console.log("querySnapShot: ", querySnapshot);
let loc = querySnapshot.docs.filter((doc) => ({
lat: doc.data().lat,
lng: doc.data().lng,
}));
console.log("locationsLOc: ", loc);
allLocations = [...allLocations, ...loc];
setLocations(allLocations);
});
});
} catch (error) {
console.log(error);
}
};
fetch();
}, [])
PLEASE HELP; I've been stuck for a week already trying to get this data.