Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Cloud Firestore rules - How do I check if a key is null

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:

  1. resource.data.assignee == null - Does not work (Error)
  2. !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';

like image 742
Gal Bracha Avatar asked Oct 08 '17 11:10

Gal Bracha


People also ask

What file should be used for firestore rules firestore rules?

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.

How do I check if a firestore field is empty?

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.

Is firestore key-value?

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.


3 Answers

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'])
like image 185
Callam Avatar answered Oct 13 '22 02:10

Callam


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) 
like image 38
pdkn Avatar answered Oct 13 '22 02:10

pdkn


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

like image 5
Sagiv Ofek Avatar answered Oct 13 '22 04:10

Sagiv Ofek