Home > Net >  Firestore only allow modification of field if user not contained in array
Firestore only allow modification of field if user not contained in array

Time:03-03

I have a document like

Field Score: number
Field usersThatRated: array 

How can I enforce in the firestore rules that only users whose id is NOT included in the usersthatRated array are allowed to increment/decrement the score?

CodePudding user response:

You can try using the following security rules:

match /collection/{docId} {
  allow read, write: if (request.resource.data.diff(resource.data).affectedKeys().hasAny(['usersThatRead']) && 
    !(request.auth.uid in resource.data.usersThatRead));
}

The hasAny is just to check if usersThatRead field is being updated. If yes, then check if user's UID is already present in that array or not.

in operator is used to check if a value is present in given array.

  • Related