0

I wanna query only the users with the subcollection Favoris (not everyUsers had a favoris subcollection) and I wanna query only the document from favoris with the same id as the current user.

I did the following function but I have no document found. I'm supposed to have one. Did I forget something?

const getFavoris = () => {
  userDB.doc()
        .collection('favoris')
        .where('id', '==', currentUser.id)
        .get()
        .then((querySnapshot) => {
          console.log('cmb', querySnapshot.size);
          querySnapshot.forEach((doc) => {
            console.log(doc.id);
          });
        });
};

also an example of my DB user and subcollection Favoris

enter image description here

enter image description here

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Xwingoga06
  • 99
  • 1
  • 10

1 Answers1

1

Since "favoris" is a subcollection, instead of using a collection() call, you should use a collectionGroup() query like in the following lines of code:

const getFavoris = () => {
      firebase.firestore()
      .collectionGroup('favoris') //
      .where('id', '==', currentUser.id)
      .get()
      .then((querySnapshot) => {
        console.log('cmb', querySnapshot.size);
        querySnapshot.forEach((doc) => {
          console.log(doc.id);
        });
      });
  };

Besides that, don't forget to create the corresponding index.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • Can you help me with the rootRef ? what is it exactly ? – Xwingoga06 Oct 26 '21 at 13:48
  • I just edited my answer. Does it work now? – Alex Mamo Oct 26 '21 at 13:49
  • yes i have just this comment , they ask me to add an exception, which i did and now i have this promise rejection : ossible Unhandled Promise Rejection (id: 0): FirebaseError: The query requires a COLLECTION_GROUP_ASC index for collection favoris and field id. That index is not ready yet. – Xwingoga06 Oct 26 '21 at 13:54
  • Yes, that is correct. I just updated my answer. – Alex Mamo Oct 26 '21 at 13:55
  • i don't understad how to create my index, i'm new with firestore :( – Xwingoga06 Oct 26 '21 at 13:58
  • Try to find a URL in the error message, or create it manually in the Firebase console. It should be a collection group index with an ascending direction (COLLECTION_GROUP_ASC). – Alex Mamo Oct 26 '21 at 13:59
  • 1
    it's ok, it's working !! thank you for everything :) – Xwingoga06 Oct 26 '21 at 14:01
  • last question ? How i can do if i wanna catch all the information of the user with favoris ?(to go back on the collection ) – Xwingoga06 Oct 26 '21 at 14:08
  • You should then perform separate queries. All queries in Firestore are shallow, it can only get documents from the collection that the query is run against. – Alex Mamo Oct 26 '21 at 14:27