John D
John D

Reputation: 3

Firebase Collection Group Query in VueJS

enter image description here

created() {
              firebase.auth().onAuthStateChanged((user) => {
            if (user) {
                this.userID = user.uid;
                console.log(this.userID);
            } else {
                console.log('User is not logged in.');
                this.$router.push('/login');
            }
         });
  },
  data() {
    return {
      pantry: [],
      userID: '',
    };
  },
  methods: {
    getCategoryDataFromFirebase() {
      const db = firebase.firestore();
      db.collectionGroup("pantry")
        .where("UserID", "==", this.userID)
        .get()
        .then((querySnapshot) => {
          querySnapshot.forEach((doc) => {
            this.pantry.push(doc.data());
          });
        })
        .catch((error) => {
          console.log("Error getting documents: ", error);
        });
    },
  },
};

I am attempting to do a Collection Group Query where I grab all of the listings in my firestore database that are associated with the user ID that created them. I am able to get the user ID on the created hook and store it in my this.userID. I want to then use that ID on my getCategoryDataFromFirebase function to do the collection group query. It's recommended to create the collection group query and get the SDK error back from firebase in the console, then use the attached link in the console to create the appropriate rules automatically instead of manually which I did. Now I am thinking that I must not be referencing the group correctly because I am unable to get any data back from my firestore. I have tried to create the group by the main "pantry" but I am thinking that I would possible need to drill down further into the database or to set up the query another way. I would appreciate any guidance that could be given. I have attached the view of my firestore as well for reference. I am attempting to get all of the userIDs in each category i.e. fruits, vegetables, etc.

Upvotes: 0

Views: 337

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598688

When you use db.collectionGroup("pantry") you are reading from all collections named pantry. In your code that is only a single top-level collections.

If you want to read from all Vegetables collections, you need to query db.collectionGroup("Vegetables").

Upvotes: 1

Related Questions