bibscy
bibscy

Reputation: 2708

How to set indexOn rule on firebase with auth.uid variable?

I am trying to set a rule on a node in firebaseDatabase, but I get error

Error saving rules - Line 85: Key names can't contain ".", "#", "$", "/", "[", or "]" (unbound names start with "$")

As I understand auth.uid is a global variable for the current logged in user. How can I fix this?

{
  "rules": {
    ".read": "auth != null",
    ".write": "auth != null", 

        "notifications/auth.uid": {
        ".indexOn":["createdAt"]    
      }
  }
}

Upvotes: 1

Views: 562

Answers (2)

Frank van Puffelen
Frank van Puffelen

Reputation: 598728

If you're trying to store notifications for each user under their auth.uid and allow querying those by defining an index, then you're looking for these rules:

{
  "rules": {
    ".read": "auth != null",
    ".write": "auth != null", 

    "notifications": {
      "$uid": {
        ".indexOn":["createdAt"]    
      }
    }
  }
}

The $uid here is a wildcard, and applies to each node under notifications. To learn more about this, see Using $ Variables to Capture Path Segments.

Upvotes: 3

Jay
Jay

Reputation: 35648

This is the issue

"notifications/auth.uid"

as it's treating everything inside the quotes as a string so the period is causing the error and paths cannot include a period character. Also, it will not resolve the auth.uid as it's just a string, not the variable you want. You could do something like

root.child('notifications').child(auth.uid) {...

or even

root.child( 'notifications/' + auth.uid ) {...

Upvotes: 1

Related Questions