0

I have two collections section1 and section2. Collection section2 has a field doc_id, it's a reference type field and represents a relationship between section1 and seciton2.

enter image description here

I want to retrieve data from section2 for given value for doc_id field. check the sample codes it works fine when I filter data with any other field such as district. But it does not work with reference field type fields

This gives expected result

const getDocumentData = async () => {
    const q = query(
      collection(db, "section2"),
      where("district", "==", "dhanbad")
    );

    const querySnapshot = await getDocs(q);
    querySnapshot.forEach((doc) => {
      console.log(doc.id, " => ", doc.data());
    });

Code works but I don't get the values. It returns null.

   const getDocumentData = async () => {
    const q = query(
      collection(db, "section2"),
      where("doc_id", "==", "H0ovBXfrwen32Xb4Ig9A")
    );

    const querySnapshot = await getDocs(q);
    querySnapshot.forEach((doc) => {
      console.log(doc.id, " => ", doc.data());
    });
Raju Singh
  • 455
  • 1
  • 6
  • 15

1 Answers1

0

As you can see in the screenshot, a document reference field is equivalent to the entire reference to that document (from the root of the database). So you can't just specify the document ID, but have to specify an actual document reference.

const docRef = doc(db, "section1", "H0ovBXfrwen32Xb4Ig9A");
where("doc_id", "==", docRef)

Also see Renaud's answer to: Querying by a field with type 'reference' in Firestore

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807