skip to Main Content

I have a simple firestore collection where I need to fetch all the records where the student id matches the key (circled in red in img) inside students.

const q = query(classessRef, where("students.key", "==", "6CgDymxFqFVgTLef2IMhlu5Sxlm2"));
const querySnapshot = await getDocs(q);

Expected Output: Should return all the classes record where students field has 6CgDymxFqFVgTLef2IMhlu5Sxlm2 in it.

Firestore structure

2

Answers


  1. Chosen as BEST ANSWER

    I was able to figure out the query to fetch all the records which match the particular key.

      const userId = '6CgDymxFqFVgTLef2IMhlu5Sxlm2';
      const q = query(classesRef, where(`students.${userId}`, "!=", null));
      const querySnapshot = await getDocs(q);
    

  2. What you’re trying to do isn’t excactly possible with the data you have now. That string "6CgDymxFqFVgTLef2IMhlu5Sxlm2" is neither a field nor a value in that document. It’s just part of the path of a field. An example of the full path of a field that you can use in a query is "students.6CgDymxFqFVgTLef2IMhlu5Sxlm2.email".

    So, you could use that email field (or any other nested field name under "students.6CgDymxFqFVgTLef2IMhlu5Sxlm2"), if you assume that the field always exists for that student ID. For example:

    const q = query(classessRef, where("students.6CgDymxFqFVgTLef2IMhlu5Sxlm2.email", ">", ""));
    

    Or you could create a whole new top-level array type field and add that ID string to it, using an array-contains query to filter for it.

    See also:

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