Kartik Watwani
Kartik Watwani

Reputation: 657

Number of update fields in firestore security rules

I am making batch operation from client to update only one field but while making batch operation and on testing in security rules It is observed that more than one fields are being updated. I checked this using request.resource.data.size() >1 and request.resource.data.keys().size()>1 returning true(document being updated) but this is not intended as I want to check in security rules that only one field is being updated using checks like request.resource.data.keys().hasOnly(['someFieldToUpdate']) but this is not working now, previously I remember there was writeFields to check that but it is not present now in documentation and also this answer mentions it. So how can I check the fields which are actually being updated in batch operations now ?

Upvotes: 2

Views: 914

Answers (2)

phatmann
phatmann

Reputation: 18493

You can use the new diff() method on the data map. It tells you what keys are changed. Here is a sample:

function isUpdateToOpenField(attr) {
    return request.resource.data.diff(resource.data).changedKeys().hasOnly(['open']);
}

allow update: if isUpdateToOpenField(request.resource.data);

Adapted from this answer.

Upvotes: 9

Frank van Puffelen
Frank van Puffelen

Reputation: 599081

The request.resource.data field contains the resource as it will exist after the write operation has succeeded. The writeFields property was removed since it could not always reliably be populated.

Right now the only option I can think of is to check if each individual field has changed, and then only allow it if there's one change. But to be honest, that sounds like an odd use-case. A more common use-case I see it to limit what specific fields the user can update, not how many they can update at once.

Upvotes: 3

Related Questions