Skip to content
Advertisement

Not able to retrieve data from firebase firestore

I am saving data to firebase successfully

    const productsRef = db.collection("store").doc(userID).collection("products");

    productsRef
      .doc(productID)
      .set({
        userID: userID,
        productCatagory: productCatagory.value,
        productCode: productID,
        productName: productName.value,
        price: price.value,
        description: description.value,
        time: time,
      })
      .then(function () {
        console.log("Document successfully written!");
      })
      .catch(function (error) {
        console.error("Error writing document: ", error);
      });

But when i try to retrieve it firestore sends “No such document”. Trying to get the array of objects.

db.collection("store")
      .doc(userID)
      .get()
      .then((doc) => {
        if (doc.exists) {
          console.log(doc.data());
        } else {
          // doc.data() will be undefined in this case
          console.log("No such document!");
        }
      })
      .catch(function (error) {
        console.log("Error getting document:", error);
      });

Here is the db

enter image description here

Edit: I found out that in order to access all documents you have to do it this way.

db.collection("store")
      .get()
      .then((querySnapshot) => {
        querySnapshot.forEach((doc) => {
          // doc.data() is never undefined for query doc snapshots

          console.log(doc.data());
        });
      })
      .catch((e) => {
        console.log(e);
      });

It goes into the then block but then querySnapshot.forEach doesnt run

Advertisement

Answer

Okay so i found the solution.

db.collection(`store/${userID}/products`)
      .get()
      .then((querySnapshot) => {
        querySnapshot.forEach((doc) => {
          
          console.log(doc.data());
        });
      });
  

   
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement