Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to increment a map value in a Firestore array

I have a firestore firebase database , in which I have a collection users there is an array in the collection and in the array there is a map in map there is a field qty.. I want to increment that qty value..

image

using increment doesnt help as the qty is inside a array index

    db.collection("users").doc(checkId).update({
                myCart: firebase.firestore.FieldValue.arrayUnion({
                    qty: firebase.firestore.FieldValue.increment(1),

                }),

this is the error Output => Uncaught (in promise) FirebaseError: Function FieldValue.arrayUnion() called with invalid data. FieldValue.increment() can only be used with update() and set()

like image 365
Mehtab Singh Edhan Avatar asked Dec 13 '22 10:12

Mehtab Singh Edhan


1 Answers

My answer below won't work, given that the qty is in an array. The only way to update an item in an array is to read the entire document, update the item in the array, and then write the entire array with the updated item back to the document.


An alternative would be to use a map instead of an array, and then update the qty using the approach outlined in my (old, and non-working) answer below 👇

You need to specify the full path to the field you're trying to update. So I think in your case, that'll be:

db.collection("users").doc(checkId).update({
  "myCart.0.qty": firebase.firestore.FieldValue.increment(1)
}),
like image 148
Frank van Puffelen Avatar answered Dec 24 '22 13:12

Frank van Puffelen