Firestore DB model, Attribute in document or subco

2019-08-28 03:49发布

I often come across this split roadwhen modeling Firebase/Firestore, perhaps you can shed light on this.

If I have multiple admins who can each clients (100s) under their name. The admin can't see the other admin clients (consider them like separate companies). What would be better?

1) Add Clients root collection and under it add a document with ID being the admin email and under that a subcollection with clients documents:

Firestore-root
   |
   --- Clients(collection)
         |
         --- Admin ID/Email(Collection)
              |
              ----------Clients Info (documents)

2) OR Add clients root collection with clients documents under it but an attribute in every document would be the admin email:

Firestore-root
   |
   --- Clients(collection)
         |
         --- Clients Info (documents)
             |
              --- AdminId: (email)

I find the first one is easier to query and most importantly more readable if you want to view the data in the console during testing/or even production. But I find the second one is less number of levels.

What is the right way to approach this? Thank you

1条回答
爷、活的狠高调
2楼-- · 2019-08-28 04:19

There is no right way for a database structure. The right solution for your database, is the solution that fits your needs and makes your job easier. My opinion regarding your database schema is related actually on what you really want to achieve.

If you want to query your database to get only the clients that correspond to a particular admin, then you can go ahead with the first option. If you want at some point to get all the clients from your database, then the second option will help you achieve this. So it might be an option to use both options.

But, if you want to achieve the same thing using the second option, this can be possible only if you'll use a query that is based on a single property (the uid property) like this:

FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference clientsRef = rootRef.collection("Clients");
Query query = clientsRef.whereEqualTo("uid", uid);

But if you want instend to achieve the same thing as in the first option and use a query that looks like this:

Query query = clientsRef.whereEqualTo("uid", uid).orderBy("aProperty", Query.Direction.ASCENDING);

You need to know that you cannot achieve this. This is not possible because in this case you need to create an index and you cannot create manually an index for each uid.

One more thing, I recommend you to use the uid instead of an email address as the document key.

查看更多
登录 后发表回答