Ad

How To Query Firebase Items With Specific Reference Type

I have a parent collection categories and it child collection directoriesDirectories connected with Categories via Category property

enter image description here

I want to query all directories with category equal to level

this.firestore
      .collection<any>('directories', ref => ref.where('categories', '==', 'levels'))
      .get()
      .pipe(
        map(x => {
          const out: [] = [];
          x.forEach(y => {
            out.push(y.data());
          });
          return out;
        })
      );

I am getting an empty array in return. How would you fix that?

UPDATE based on the answer provided by @renaud-tarnec:

const categoryDocRef = this.firestore.doc('categories/levels');
this.firestore
      .collection<any>('directories', ref => ref.where('categories', '==', categoryDocRef))
      .get()
      .pipe(
        map(x => {
          const out: [] = [];
          x.forEach(y => {
            out.push(y.data());
          });
          return out;
        })
      );

Now having an error core.js:15713 ERROR Error: Function Query.where() called with invalid data. Unsupported field value: a custom AngularFirestoreDocument object

Ad

Answer

If you want to use the DocumentReference data type in a query, you have to build a DocumentReference and use it in your query, as follows (in "standard" JavaScript):

        const categoryDocRef = firebase.firestore().doc('categories/levels');

        firebase.firestore().collection("directories").where("parent", "==", categoryDocRef)
        .get()
        .then(function(querySnapshot) {
           querySnapshot.forEach(function(doc) {
              console.log(doc.id, " => ", doc.data());
           });
        })
        .catch(function(error) {
           console.log("Error getting documents: ", error);
        });

I've made the assumption that the documents containing the field parent (which , in turn, contains the DocumentReference type data) are in a collection named directories.


UPDATE: It appears that the following won't work with angularFire2, see the comments

So, if I am not mistaking, this would be done as follow in angular, based on the code of your question:

const categoryDocRef = this.firestore.doc('categories/levels');

this.firestore
      .collection<any>('directories', ref => ref.where('parent', '==', categoryDocRef))
      .get()
      ...
Ad
source: stackoverflow.com
Ad