skip to Main Content

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


  1. 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:

    • Replicate the email of each user in their school document, and using an array-contains query to then find the school.
    • Using a collection group query on all users collections to find the correct user(s), and then going up the ref.parent().parent() chain of the document snapshots to find the school for each result.

    Also see:

    Login or Signup to reply.
  2. 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 with getDoc() query and schoolId will be there already.

    Hope this helps 😁

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search