Home > Net >  Firebase obtaining multiple documents from a collection not working
Firebase obtaining multiple documents from a collection not working

Time:01-16

I'm using a datepicker in a food ordering webpage, the date selected by the user is stored in a variable called dateSelected, then, the following function is used to get the data depending on the date they selected:

const q = query(collection(db, "cities"), where("capital", "==", true));

const querySnapshot = await getDocs(q);
querySnapshot.forEach((doc) => {
  // doc.data() is never undefined for query doc snapshots
  console.log(doc.id, " => ", doc.data());
});

However, nothing is logged in the console. If I only console log the querySnapshot, the result in the console is the following:

xu {_firestore: ka, _userDataWriter: ah, _snapshot: Fo, metadata: Du, query: Aa}

I tried this:

const q = query(collection(db, "/Dishes/All/Lunch"), where("dates", "==", dateSelected));
    const querySnapshot = await getDocs(q);
    querySnapshot.forEach((doc) => {
      // doc.data() is never undefined for query doc snapshots
      console.log(doc.id, " => ", doc.data());

    });

});

console.log(doc.id, " => ", doc.data());

This line above appears to be the line that is not working

Here's an example of a date picked that matches the one in firebase and what is logged in the console after picking it:

My code

Console

CodePudding user response:

dates is an array that will never be equal to a string. If you want to query all lunch documents where dates array contains a given date, then try using array-contains operator instead:

const q = query(collection(db, "/Dishes/All/Lunch"), where("dates", "array-contains", dateSelected));
const querySnapshot = await getDocs(q);

console.log(querySnapshot.size)
  • Related