Ujjwal Chadha
Ujjwal Chadha

Reputation: 143

Firebase Firestore Security Rules: Allow subset of fields

I have a database where my user document can have the following fields:

['name', 'email', 'dob', 'gender', 'country', 'profile', `notificationToken`]

I want the document to be created when the request document has a subset of these fields Neither hasAll() works here (as to-be-created document might not have all fields) nor hasAny() works (as to-be-created document must not contain an invalid field like 'photo').

Plus, I want that if a field, for example, 'name' is present, it should be a string. Now if I use:

allow create, update: if request.resource.data.name is string

And if the name field is not present in my to-be-created document, (which would be the case if I set the notificationToken field later and use setOptions.merge()), it returns false or error as I am not setting the field. But I want it to only force that string datatype if the field is present. I also want to do the same where I can set the profile object individually and use merge, but also forcing the datatype.

Is there a way to accomplish this in security rules?

Upvotes: 2

Views: 297

Answers (1)

Michael Lehenbauer
Michael Lehenbauer

Reputation: 16309

To check for a subset of fields you can use hasAll in the opposite direction to achieve the desired effect, e.g.:

allow create, update: if ['name', 'email', 'dob', 'gender', 'country', 'profile', 'notificationToken'].hasAll(request.resource.data.keys());

Upvotes: 1

Related Questions