In Cloud Firestore Rules - I have a document called task
and I want to see if some data (assignee
field) is null / don't exists.
I've tried:
resource.data.assignee == null
- Does not work (Error)!resource.data.hasAll(['assignee'])
- Does not work (Error)From the documentation - it states that this indeed creates an error:
// Error, key doesn't exist
allow read: if resource.data.nonExistentKey == 'value';
rules // is a file used to define the security rules for your Firestore database. firestore. indexes. json // is a file used to define indexes for you Firestore queries.
Because every document in a Cloud Firestore database is a Map, you can use size() method to see if is empty or not. Show activity on this post. In order to check if the Document incoming is empty, you can check for the number of keys of the stored object. If there are 0 keys stored, you can then delete the document.
Cloud Firestore is a NoSQL, document-oriented database. Unlike a SQL database, there are no tables or rows. Instead, you store data in documents, which are organized into collections. Each document contains a set of key-value pairs.
Reading the list comparisons of the Firestore Security rules documentation here, we can see that hasAll
returns true if all values are present in the list.
// Allow read if one list has all items in the other list
allow read: if ['username', 'age'].hasAll(['username', 'age']);
The request.resource.data
is a map containing the fields and values. In order to use hasAll
, we must first get the keys as a list of values as shown here.
!resource.data.keys().hasAll(['assignee'])
Looking at the docs - https://firebase.google.com/docs/reference/rules/rules.Map
k in x - Check if key k exists in map x
so this should work (without the keys())
!('assignee' in resource.data)
if you want to make sure a key is null you need to check that this key is not part of the resource keys property:!resource.data.keys().hasAny(['assignee'])
you can also use hasAll
or hasOnly
. more info here
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