0

I am working on a Android Food delivery app. Till now I managed to create a real time database from Firebase and also managed user logins using Authentication in Firebase.

To manage their orders we planned to add a cart(add to cart option) for each user. How to manage a unique cart for each user so that all the orders wont get mixed up and can be tracked easily I can only use firebase?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Vemuri Pavan
  • 495
  • 7
  • 15

1 Answers1

3

A simple way to get started is to store the cart for each user under a separate top-level node:

carts
  $uid
    item1: ...
    item2: ...

The $uid here is just a placeholder where you'll use the UID of the current user.

This structure allows you to easily look up the cart for the current user, without loading the data for other users. You can also easily secure access to this data, so that users can only see their own cart. See the documentation on securing user data for more on that.

You'll typically only store the ID of each product in the cart in a structure like this:

carts
  $uid
    itemid1: true,
    itemid2: true

To learn more about storing sets instead of arrays, read my answer here: http://stackoverflow.com/questions/40656589/firebase-query-if-child-of-child-contains-a-value

These IDs then refer to a global list of products, which you store in another top-level list:

products
  $productid
    itemid1: { ... },
    itemid2: { ... }

Now each time you load the user's cart, you'll also load the details of each product they have in the cart. Firebase doesn't support server-side joins, so you'll have to do this from the code in your app.

An alternative is that you duplicate some of the data for the products into the carts of the users that have that product. If you duplicate the information that you'll need to show the user's cart, you won't have to read the separate products to show the cart. This type of data duplication is called denormalization, and is quite normal in Firebase and other NoSQL databases.

See also:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807