I have this issue and can’t figure out how to solve it, addDoc() and setDoc() functions separately without using "if" "else" work correctly, but when I use "if" "else" it gives me this error.
"Error adding product to cart: TypeError: Cannot read properties of undefined (reading ‘quantity’)"
It is a function to add a product to the cart, it must check if the document is already in the subcollection, then increase quantity +1, otherwise create a document, taking the name of the product as the document id.
I’am using Vue.js 3 and Firebase 9.
const productRef = doc(db, "carts", cartId, "cartProducts", this.productName);
const productDoc = await getDoc(productRef);
if (productDoc.exists) {
await updateDoc(productRef, {
quantity: productDoc.data().quantity + 1
});
} else {
await setDoc(productRef, product);
}
2
Answers
solved using runTransaction
The error
indicates that the field
quantity
is undefined in theproductDoc
.So either you enforce through security rules that
quantity
has a correct value when theproductDoc
doc is created/updated or you adapt your code to handle this case as follows, for example: