简体   繁体   中英

What is the best practice for storing shopping basket in Firestore?

I'm creating a flutter app which needs shopping basket functionality. I'm using Firestore to save the contents of user's shopping baskets but do not know how best to do this.

At the moment, I have a collection called 'baskets' which contains documents (with the users id as the reference).

Within these documents, should I have a field which is a dictionary/map with key = productID and value = quantity, or should I just create a field for every product that the user adds to their basket?

Or is there a better way altogether (still using Firestore).

You are on the right track. Creating a root collection called baskets , under which each user has its own document based on the user's unique UID is good. Now, inside each of the user's documents, you can add a sub-collection called cartItems , where you will hold a document per product.

For each product then you can add its name , price , and amount and other descriptive product fields. That way instead of having multiple documents of the same product, just add a document per product, and a field called amount which you increment as users add more items of that same product.

You will be able to calculate how much is the total cost of their cart by pulling all documents, adding up all the amount fields of products times their individual prices, etc.

You can increment / decrement the amount of products, or altogether remove the product from their basket by removing the product document.

The main collection baskets should look like this:

在此处输入图像描述

While your cartItems subcollection could look like this:

在此处输入图像描述

Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM