manidos
manidos

Reputation: 3464

"Null value error" in firestore simulator

I'm trying to reproduce an example from the official Firestore docs. Everything you need to know is on the screenshot. Is it a bug or am I missing something?

enter image description here

Upvotes: 22

Views: 12008

Answers (5)

user2522885
user2522885

Reputation: 615

I'm still learning but the issue with

allow read: if (resource == null) || (resource.data.visibility == 'public')

is when you use such a rule for /cities/{doc}. From what i can see resource == null whenever you search for documents without an exact document ID; the above rule would show everything, private and public, for /cities/{doc} because resource always == null.

From what i've been able to piece together one must make use of the get(...) statement to directly access a document's data whenever within a match that can return 1 or more documents, so

get(/database/...).data.visibility == 'public'

Upvotes: 1

Johan Witters
Johan Witters

Reputation: 1636

The issue is - as manidos - pointed out that the document /cities/moscow doesn't exist and hence the document is not accessible. However, a cleaner way to specify your rule is:

allow read: if (resource == null) || (resource.data.visibility == 'public')

It allows an application to query data that doesn't exist without blowing up with a security exception.

Upvotes: 7

funct7
funct7

Reputation: 3601

A bit more explanation would have made manidos's answer a good one.

It seems like resources should be used only for rules involving data that have been already written; e.g. delete, read, update, etc.

If you want to set rules on data that "will be" written, use getAfter.

Upvotes: 6

Jay
Jay

Reputation: 35657

The key is to reading through the comments.

Many apps store access control information as fields on documents in the database. Cloud Firestore Security Rules can dynamically allow or deny access based on document data:

and then

// Allow the user to read data if the document has the 'visibility' field set to 'public'

If you look at the example data provided in the guide

let citiesRef = db.collection("cities")
citiesRef.document("SF").setData([
    "name": "San Francisco",
    "state": "CA",
    "country": "USA",
    "capital": false,
    "population": 860000,
    "regions": ["west_coast", "norcal"]
])

There is no 'visibility' field, however there is a name, state country field etc.

If you want to work with that data set, add a 'visibility' field to each city and set it's value to 'public'

 citiesRef.document("SF").setData([
        "name": "San Francisco",
        "visibility": "public"

Upvotes: 3

manidos
manidos

Reputation: 3464

The problem is that there's no actual document at /cities/moscow

Upvotes: 20

Related Questions