My data is stored in Firestore in below model.
My Problem is, I want to get schoolid of logged-in email id.
Data Model:
instituteData->schoolid->users->email->data
What I tried
const q = query(collection(db, "instituteData"), where("email", "==", "[email protected]"));
const querySnapshot = await getDocs(q);
querySnapshot.forEach((doc) => {
// doc.data() is never undefined for query doc snapshots
console.log(doc.id, " => ", doc.data());
});
Screenshot of Data Structure
Screenshot of Data Structure
2
Answers
Firestore queries can only filter on data in the documents that they return. So unless the
email
field is. inside the school documents, your query won’t work.The common workarounds are to:
array-contains
query to then find the school.users
collections to find the correct user(s), and then going up theref.parent().parent()
chain of the document snapshots to find the school for each result.Also see:
As far as I know, there are no inner queries in firebase like we have in SQL, and your approach looks like the SQL table approach, clearly, your structure will not work well in firebase. You shouldn’t make SQL-like structure in NoSQL, I learned this hard way.
one solution I can think of is to store the id of parent collections in child collection and all of their documents.
Basically, you are passing ids parent to all children. ¯(ツ)/¯
In your case
you should store
schoolId
in all its students, then you can directly get that document withgetDoc()
query andschoolId
will be there already.Hope this helps 😁