Firestore has a DocumentReference type, which is a "pointer" to another firestore document. Using the firebase JavaScript client, you can access properties (e.g. document "id"), directly on the reference.
For example, if there is a document with a docRef
property that is a firestore DocumentReference:
const retrievedDoc = await getFirestoreDocument(); console.log(retrievedDoc.docRef.id); // "jRmSeMYDMKiOPGsmkdaZ"
I am trying to accomplish the same thing within firestore rules. There is a custom function named isOwner
. It uses the firestore rules get
call on a document path, and then attempts to access the docRef.id
just as if it were the JavaScript client above.
get(/databases/$(database)/documents/path/to/$(id)).data.docRef.id
The value of the document's id is compared against the current user's. But when I test this using the simulator and in real code, it fails. I feel like this should work, but it doesn't.
What does work is to store and use the id value directly as a string (e.g. get(/path/id).docId
) instead of a DocumentReference.
Should I be able to access the id
value of a DocumentReference within the firestore rules? Am I doing something wrong?
I want to avoid doing a second document get
within the rule as described in this SO answer. That's a second "read" for each trigger of this rule. And I don't think the document id (which is what I need) will be available on the get
call anyway.
rules // is a file used to define the security rules for your Firestore database. firestore. indexes. json // is a file used to define indexes for you Firestore queries.
< T > A DocumentReference refers to a document location in a Firestore database and can be used to write, read, or listen to the location. The document at the referenced location may or may not exist. A DocumentReference can also be used to create a CollectionReference to a subcollection.
Cloud Firestore allows you to listen to the results of a query and get realtime updates when the query results change. When you listen to the results of a query, you are charged for a read each time a document in the result set is added or updated.
Based on documentation:
get()
method is supposed to returns a Resource object which is supposed to contains a .id
property (as well as .data
).
For example, to restrict write
access to an authenticated user which is the author of a book document (authors documents are identified with the user uid), you would do:
service cloud.firestore { match /databases/{database}/documents { match /books/{document=**} { allow write: if get(resource.data.authorReference).id == request.auth.uid; } } }
Yet I'm always having the error property id is undefined on object
on trying. .data
is accessible so I suppose there is an issue in the api.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With