Skip to content
Advertisement

How can I decrement a field value from firestore after submitting a form successfully?

I have these collection of items from firestore:

  • availability : true
  • stocks: 100
  • item: item1

enter image description here

I kind of wanted to decrement the stocks after submitting the form: I have these where() to compare if what the user chose is the same item from the one saved in the firestore.

JavaScript

This is how I’ll submit my form and I’ve set the incrementCounter() after saving it:

JavaScript

There’s no error in submitting the form. However, the incrementCounter() is not working and displays this error:

JavaScript

Advertisement

Answer

The where() method exists on a CollectionReference and not a DocumentReference. You also need to get references to those documents first so first get all the matching documents and then update all of them using Promise.all() or Batch Writes:

JavaScript

If you are updating less than 500 documents, consider using batch writes to make sure all updates either fail or pass:

JavaScript

You can read more about batch writes in the documentation

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