How to set foreign keys in Firestore?

jhashane :

As an instance think of an e-commerce app where a user can upload as many as items and those items have categories and subcategories.

How to set user_id as a foreign key in each items posted as well as item_id in users collection in order to query all the items posted by a specific user.

How do we make use of reference data type in Firestore to set foreign keys?

Are there any other methods to set foreign keys?

Database Structure:

Users/doc_id/name..

Categories/fashion/clothing/auto_doc_id/type:denims
Alex Mamo :

in order to query all the items posted by a specific user.

To achieve this, there is no need to set user_id as a foreign key in each items posted as well as item_id in users collection. You can only add a new property to the item object named postedBy which will hold as a value the user id. To display only the items of a specific user you need to query the database using the following code:

FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference itemsRef = rootRef.collection("items");
Query query = itemsRef.whereEqualTo("postedBy", user_id);

There is also another approach in which involves duplicating data. There is no problem with this tehnique, when it comes to Firebase. This is a quite common practice, which is named denormalization and for that, I recommend you see this video, Denormalization is normal with the Firebase Database. This is for Firebase Realtime database but the concept applies in the same way also to Cloud Firestore.

So with other words, you can create a new collection in which you can store all items that were added by a specific user. The database structure should look like this:

Firestore-root
     |
     --- users (collecton)
          |
          --- userId (document)
                 |
                 --- userItems (collecton)
                        |
                        --- itemId (document)

When you are duplicating data, there is one thing that need to keep in mind. In the same way you are adding data, you need to maintain it. With other words, if you want to update/detele an item, you need to do it in every place that it exists.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=461400&siteId=1