Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firestore security rules: check for not exists(/collection/document)

In firebase firestore security rules, I want to allow a request only if a particular document does not exist. My code is:

match /users/{user_id} {
 allow create: if !exists(/databases/$(database)/merchants/$(request.auth.uid));
}

I am pretty sure the document does not exist but it does not work. Both exists() and !exists() give false somehow, or maybe !exists() raises some error.
I have even tried:

match /users/{user_id} {
 allow create: if exists(/databases/$(database)/merchants/$(request.auth.uid)) == false;
}

Is there any way to make this work?

like image 578
Ujjwal Chadha Avatar asked Dec 23 '17 08:12

Ujjwal Chadha


People also ask

Does firestore Create collection if not exists?

If either the collection or document does not exist, Cloud Firestore creates it.

What file should be used for firestore rules firestore rules?

firestore. rules // is a file used to define the security rules for your Firestore database. firestore.

How do I query a collection in firestore?

To start querying a collection, you need to provide the hooks with a CollectionReference or Query reference created directly from the firebase/firestore library. The reference can be a simple collection pointer or a fully constrained query using the querying functionality provided by the Firestore SDK.


1 Answers

Are your rules inside the database block? Cause I had a similar problem and was actually putting the rule bellow the database block, and my rule was using the $(database)parameter just like yours

service cloud.firestore {
    match /databases/{database}/documents {
        match /users/{user_id} {
            allow create: if !exists(/databases/$(database)/merchants/$(request.auth.uid));
        } 
    }
}
like image 174
adrianolsk Avatar answered Sep 22 '22 02:09

adrianolsk