Make query with "where" filter in Firestore

I want to filter and get specific items based on the categoryID, where i use the "where" method and the "==" operator.

I have this Firestore collection called "task", where the documents are divided by userID and each document for a user contains an array of different tasks. The structur is seen here: Enter image description here

This is how i add the array tasks for an user in the task collection:

const addToFirebase = async() => {
    if(dataFetch) {
      await setDoc(doc(db, "task", `${firebase.auth().currentUser.uid}`), {
        tasks: tasks
      }, {merge: true});
    }
  }

And this is how i have tried to make my query that is not working:

 const getFilteredTasks = async() => {
    const collectionRef = collection(db, "task", `${firebase.auth().currentUser.uid}`, "tasks");
    const q = query(collectionRef, where("categoryID", "==", item.id));

    console.log('outside snapshot')
    console.log(item.id)

    const querySnapshot = await getDocs(q);
    querySnapshot.forEach((doc) => {
      console.log(doc.data());
      console.log('inside snapshot')
    });
  }

When the above function is called, it logs the "outside snapshot" and the correct item.id, which is the categoryID for each task, but it does not log the doc.data() and the "inside snapshot".

1 answer

  • answered 2022-05-04 10:59 Nicholas Tower

    You've set up your query as though each task will be a separate document in a collection, but based on the screenshot and the way you're setting the data, you just have a single document per user. That document contains all the individual tasks. So to access that you would get the document and use client side code to use the parts of the data you care about:

    const getFilteredTasks = async () => {
      const docRef = doc(db, 'task', `${firebase.auth().currentUser.uid}`);
      const snapshot = await getDoc(docRef);
      const data = snapshot.data();
      if (!data) {
        return [];
      } else {
        return data.tasks.filter(task => task.categoryID === item.id);
      } 
    }
    

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum