adravel
adravel

Reputation: 68

Firestore Security Rules - Update one specific field without providing data for the other fields

I'm new to Firestore and it's security rules. For my project, I have some simple rules for data validation that looks like this:

match /users/{userId} {
    allow create, update: if
        request.resource.data.name is string &&
        request.resource.data.age is int &&
        request.resource.data.score is int;
}

At the moment I have only tested it on the simulator and it works fine in terms of validating the data, but the problem is for each query I have to provide data for all fields/keys mentioned in the rules. For example, if I want to update the name of the user, I also need to provide the age and score data.

How should I structure my rules so it's possible to update only one specific field without providing data for the other fields?

Upvotes: 2

Views: 121

Answers (2)

Frank van Puffelen
Frank van Puffelen

Reputation: 599946

The request.resource.data variable contains the data as it'll exist after the write operation (if that succeeds), so unless your code is overwriting all fields, it should contain the merged fields of the existing document you're updating and the fields specified in the update() call.

If the rules playground doesn't follow these rules, that might be a bug in the playground. I recommend (also) testing with actual code, as I'm pretty certain that there's no bug there for update calls (as it'd lead to quite some support calls).

Upvotes: 2

Dharmaraj
Dharmaraj

Reputation: 50930

You can use get() to get a field and set a default value if it doesn't exist as shown below:

match /users/{userId} {
  allow create, update: if
    request.resource.data.get("name", "") is string &&
    request.resource.data.get("age", 0) is int &&
    request.resource.data.get("score", 0) is int;
  }
}

Checkout enforcing types for optional fields section in the documentation.

Upvotes: 2

Related Questions