Google Firestore: Store Document Id as Reference or String

Mar 31, 2019

Do you store user_id property for a document as Reference or String?

item {
    name: "Test"
    user_id: "2i5uqlufac0QvPw1YRiE"
    user_ref: "/users/2i5uqlufac0QvPw1YRiE"
}

If you use the property as part of security rules (e.g. only item owner can read the document), you need to use String.

service cloud.firestore {
  match /databases/{database}/documents {
    match /items/{item_id} {
        allow read: if request.auth.uid == resource.data.user_id;
        // the following doesn't work
        // allow read: if request.auth.uid == resource.data.user_ref.id;
        // allow read: if request.auth.uid == get(resource.data.user_ref).id;
    }
  }
}

NOTE: Based on get and Resource, get(resource.data.user_ref).id should work (but it doesn't, a bug maybe?)

Using reference provides context, as in you know the collection path is /users/*, which comes with pros and cons.

  • user_ref will return DocumentReference, else you need to construct firestore.collection("users").document(userId).
  • I suspect you need to update all user_ref if you ever change collection name or path.
  • user_ref can be used to refer to different collections (e.g. /users or /admins or private_users), just in case all users don't necessary resides in /users collection.

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.