I can't figure out how to do optional properties in Firestore. It doesn't seem to be covered in the docs and the following fails for me.
service cloud.firestore {
match /databases/{database}/documents {
function maybeString(val) {
return val == null || val is string
}
match /myCollection/{document} {
function mySchema() {
return request.resource.data.name is string
&& maybeString(request.resource.data.optionalProp);
}
allow read: if request.auth != null;
allow create, update: if mySchema();
}
}
}
service cloud.firestore {
match /databases/{database}/documents {
match /myCollection/{document} {
function mySchema() {
return request.resource.data.keys().hasAll(['name'])
&& request.resource.data.name is string
&& request.resource.data.optionalProp is string;
}
allow read: if request.auth != null;
allow create, update: if mySchema();
}
}
}
I am using the second solution but you need to check for the presence of the optionalProp
using 'fieldName' in resource.data.keys()
:
service cloud.firestore {
match /databases/{database}/documents {
match /myCollection/{document} {
function mySchema() {
return request.resource.data.keys().hasAll(['name'])
&& request.resource.data.name is string
&& (
! ('optionalProp' in request.resource.data.keys())
|| request.resource.data.optionalProp is string
);
}
allow read: if request.auth != null;
allow create, update: if mySchema();
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With