Tapas Mukherjee
Tapas Mukherjee

Reputation: 2178

Stop counter min value at 0 when using Firstore Fieldvalue increment function

Is there way I can stop my number type field value to go negative (minimum 0) when using Firstore Fieldvalue increment and not using transactions?

this.afs.doc('path').update({count: firebase.firestore.FieldValue.increment(11)});

If the field count has value 0, it will go to -1.

Upvotes: 2

Views: 1374

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317740

A transaction is actually the right way to go here, since you can check the bounds of the value. FieldValue.increment() can't do that.

However, if you want to update to simply fail when provided with invalid values, you can use Firestore security rules to validate the field value. These rules only work when directly accessed by web and mobile clients. They don't apply to backend code.

Upvotes: 1

Related Questions