Skip to content
Advertisement

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()

Advertisement

Answer

The field you want to update is embedded in an array. In this case, you can’t use FieldValue.increment(), since it’s not possible to call out an array element as a named field value.

What you’ll have to do instead is read the entire document, modify the field in memory to contain what you want, and update the field back into the document. Also consider using a transaction for this if you need to update to be atomic.

(If the field wasn’t part of an array, you could use FieldValue.increment().)

Advertisement