Angular Firestore – Search for all documents with reference to specifig document

Issue

I’m trying to search all documents in collection a with a reference to a specific document in collection b.

All I found here or on google was not working :/

My attemp in my service class

  getAsFromB(id) {
      var refB = this.firestore.collection("/collection_b").doc(id);
      console.log(refB);

      return this.firestore
        .collection("/collection_a", (ref) => ref.where("refB", "==", refB))
        .snapshotChanges();
  }

All I get is the following error: Unsupported field value: refB = custom Object but log says refB is looking good AngularFirestoreDocument

enter image description here

what did I forget or what am I doing wrong?

many thanks in advance

Solution

Your first query here:

var refB = this.firestore.collection("/collection_b").doc(id);

points to a Firestore document, but you need to specify that you want it’s reference. To fix it, change that line to this:

const refB = this.firestore.collection("/collection_b").doc(id).ref;

Here is a modified version of your function that will log out the results of your query to verify that it’s returning the expected documents:

getAsFromB(id: string) {
   const refB = this.firestore.collection("/collection_b").doc(id).ref;
   console.log(refB);

   return this.firestore
     .collection("/collection_a", (ref) => ref.where("refB", "==", refB))
     .snapshotChanges().subscribe(res => {
       res.forEach(doc => {
         console.log(doc.payload.doc.data());
       })
     });
 }

As this is in a service, you’ll want to remove the subscribe, I just thought it could be useful for your debugging 🙂

PS it’s also good practice in Typescript to use const and let instead of var.

Answered By – Hydra

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published