Michel
Michel

Reputation: 11753

How to build a path to a Firestore document in security rules using variables

I'm writing a rule to allow the creation of new document to My_Collection whose structure looks like this:

field1="value-1"
field2="value-2"
field3="other-miscellaneous-values"

This should be allowed only if there is no document in Side_Collection with a document ID using the following format:

value-1:value-2

Where "value-1" comes from the document field "field1", and "value-2" comes from "field2", and they are delimited with a colon.

Here is the rule I am trying:

allow create: if !exists(/{database}/Side_Collection/{request.resource.data.field1}:{request.resource.data.field2});

And this is the kind of error messages I get:

Error saving rules - Line 24: Unexpected '}'.; Line 24: Missing 'match' keyword before path.; Line 24: Unexpected '.'.; Line 24: mismatched input 'request' expecting '}'; Line 24: Unexpected ':'.; Line 24: Unexpected ')'.; Line 30: Unexpected 'match'. 

I tried a few variations of the above, but nothing works.

Upvotes: 1

Views: 967

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317402

If you want to insert some variable value or expression inside a path construction, you have to use $() to isolate that expression. This is discussed in the documentation for accessing other documents.

In your case, you probably want to build the path to pass to exists() like this (I added carriage returns for readability, you will want to remove them):

exists(
  /databases
  /$(database)
  /documents
  /Side_Collection
  /$(request.resource.data.field1 + ":" + request.resource.data.field2);

Upvotes: 3

Related Questions