Firestore: Clients and invoices, how to model it

2019-06-08 11:43发布

I have the following schema and I am not sure how to model it in Firestore.

I will be having clients and invoices. Clients "has" invoices. I need to be able to do these 2 queries:

  • Show invoices that a client has
  • Update all invoices in the system (change a boolean attribute from true to false).

What would be the right way to model this? The first query is satisfied by having a collection of clients with subcollection of their invoices. But the second one is satisfied by having a collection of all invoices?

Any experienced help is appreciated

Thank you

2条回答
够拽才男人
2楼-- · 2019-06-08 12:11

I have another recommendation which involves you to create two top level collections like this:

Firestore-root
   |
   --- users (collection)
   |     |
   |     --- userId (documents)
   |          |
   |          --- //user details
   |
   --- invoices (collection)
         |
         --- invoiceId (documents)
              |
              --- yourBooleanProperty: true
              |
              --- userId: true

As you can see, the simplest way to achieve this, is to have a single collection named invoices that can hold as documents all the invoices in your database. Because a single invoice can belong only to a single user, you can have the userId as a property. To get all the invoices that correspond to a specific user, I recommend you to use the following query:

FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
Query query = rootRef.collection("invoices").whereEqualTo(userId, true);

And if you want to change the boolean property of all invoices from true to false at once, simply use the following query:

Query query = rootRef.collection("invoices").whereEqualTo(yourBooleanProperty, true);
查看更多
我命由我不由天
3楼-- · 2019-06-08 12:38

Remember that Firestore uses a document-oriented NoSQL model, similar to MongoDB and CouchDB, which leads to fundamentally different data structuring decisions.

You can think this structure in a relational way, and you can achieve the same results.

And you already did that here

The first query is satisfied by having a collection of clients with subcollection of their invoices.

so in order to solve your last requirement i would make a collection with all the invoices and then share with the clients invoice the current invoice id, so you will have inside your first query a subcollection with the ids to refer to your all invoices, this way you can refer to them and make any changes you want just querying the first collection.

let me just illustrates how they can connect

enter image description here

查看更多
登录 后发表回答