3
votes

I've a counter in firestore that count likes. And I increment it like this:

const db = firebase.firestore();
const increment = firebase.firestore.FieldValue.increment(1);

// Document reference
const doc = db.collection('coll').doc('doc');

// Update read count
doc.update({ likes: increment });

So if someone edits the source and replaces increment with decrement, it's going to work that way. I'd like to prevent that.

How can I write a firestore-security rule for this so that the rule only allows incrementing and not decrementing?

2

2 Answers

10
votes

And if you want to enforce an increment by 1:

allow update: if request.resource.data.likes == resource.data.likes + 1;
6
votes

You can ensure that the new value is greater than the previous value with a Security Rule like the following one:

allow update: if request.resource.data.likes > resource.data.likes;

BTW, note that FieldValue does not have a decrement() method. If you want to decrement, you need to use a negative number:

const decrement = firebase.firestore.FieldValue.increment(-1);