39

Firestore has recently launched a new feature to increment and decrement the integer values atomically.

I can increment the integer value using

For instance, FieldValue.increment(50)

But how to decrement ?

I tried using FieldValue.decrement(50) But there is no method like decrement in FieldValue.

It's not working.

https://firebase.googleblog.com/2019/03/increment-server-side-cloud-firestore.html?linkId=65365800&m=1

A K
  • 589
  • 1
  • 4
  • 12

2 Answers2

94

To decrement the value in a field, do a negative increment. So:

FieldValue.increment(-50)
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • 2
    hahaha, I wonder why the OP didn't think of a negative parameter in the first place! Knowing the signed range of numeric datatypes is taken for granted nowadays... Anyway, in OP's defense, I would say that this `increment` method can be more aptly named as `tally`! :P – varun May 12 '19 at 13:18
  • `FieldValue` alone wasn't working. Then realized I need this `const FieldValue = require('firebase-admin').firestore.FieldValue;`. Thanks to: https://stackoverflow.com/a/47108530/2162226 – Gene Bo Jul 16 '19 at 23:05
  • Unfortunately the way to reach the correct method is slightly different on each platform. That's indeed the syntax on the Admin SDK for Node.js, although I usually do it as `admin.firestore.FieldValue.increment(-50)`. – Frank van Puffelen Jul 16 '19 at 23:22
  • 1
    Thanks for this, Google made no mention of this in their documentation. – Supertecnoboff Sep 16 '19 at 12:26
  • 1
    is there any way to avoid negative value while decrementing? In my case, the field value is set to 20, when I decrement by 30, it goes to -10, which I don't want. I want the value to stop at 0. – Soorya May 13 '20 at 12:58
  • There's no way to truncate the value, but you could reject that increment with security rules. If you're having trouble making that work, post a new question with what you tried. – Frank van Puffelen May 13 '20 at 14:22
  • @Soorya you can also get the value of the field first and then conditionally make update call if the value is (for example) equal or over 30. – Hessuew Sep 03 '21 at 07:24
3

Make sure you're not accessing FieldValue from a Firestore instance. Eg. (in node.js with admin sdk)

admin.firestore().FieldValue.increment(-50) // Won't work
admin.firestore.FieldValue.increment(-50) // Will work

This did it for me.

eldermao
  • 633
  • 8
  • 18