AsifM
AsifM

Reputation: 699

Firestore rules: condition check fails when data is number

Below is a sample rule that fails when the document field used in the condition has a data type of number-

match message_box/{user_id}/inbox {
      allow read: if get('..../users/$(request.auth.uid)).data['user_id'] == user_id
}

This rule always fails because in data the field value is number, but in path variable {user_id} it is captured as string.

Following two tests validates that it is an actual issue-

  1. In rules, by using a hardcoded integer value on right side of the comparison (e.g.- data['user_id'] == 456), and then the read succeeds. Or-
  2. In data, set the data type of user_id field to string. In that case the match rule specified at the top of this post succeeds.

Any easy way to run it smooth? Don't see a way to cast int to string in rules documentation.

Upvotes: 4

Views: 1144

Answers (1)

JeremyW
JeremyW

Reputation: 5272

This question was referenced here.

In case anyone runs into this in the future, check out these docs on converting data types in the Firestore rules:

String -> Integer

Integer -> String

Examples:

int("2") == 2
int(2.0) == 2

string(true) == "true"
string(1) == "1"
string(2.0) == "2.0"
string(null) == "null"

Upvotes: 6

Related Questions