How to reference another collection in Firebase’s Cloud Firestore

Asked

Viewed 816 times

0

I’m starting to learn Firebase using Cloud Firestore. And I have a question: How can I relate collections? I see the collections as tables, so I would have a collection of Products, and a Category. And in the Products collection, I would have to have the ID of the Category, to specify that each is in some category, but since it’s a non-relational bank, and I’m still learning all this, I’m kind of lost. Any help I can give.

CloudFirestore

1 answer

0

You have two approaches:

In the Product you can put the Category Id, and with it you have the category reference. Another point, what I use most, is to save the category data in the Product. For example:

categoria:{ id: OHUIGDAUYG23, nome: Gastronomia}

The second case is better, because as soon as you retrieve the product information comes the category information.

You should store your data taking into account what it will display. If you do not display the Category in the Product, you do not need to store the category information, only the ID, otherwise it is interesting to store the Category information in the Product, so avoid making a new query.

I hope I’ve helped.

  • Thank you for answering! I would like to better understand the 2 cases. In 1°, you say I can only put the category ID in the Product collection, but how do I do that? I have the Product Collection, I have the automatically generated ID documents of the products I added, and in each document I have the information.. Where exactly should I add the Category ID? And this category ID I should put a name to it instead of automatically generating correct? Thanks for the help again, ask just a little patience as I am new to Firebase and also with programming.

  • When you register a Product, don’t you say which category it belongs to? You can do the following: When you register a Product, on the registration page you would have a combobox with the Categories recovered from Firebase. Fill in all the information about the Product and select a Category. With this you can save the complete information of Category, {id:ouhdiuashd, name: Gastronomy} in the Product: { name: Salmon, value: 50.00, category: {id:ouhdiuashd, name: Gastronomy}}. Or just the id: { name: Salmon, value: 50.00, category: ouhdiuashd }.

  • As I said before, it depends on how you use the Category information. Want to display the category in the Product? If yes the best option is to save all Category data in the Product: Ex:{ name: Salmon, value: 50.00, category: {id:ouhdiuashd, name: Gastronomy}}. Otherwise there is no need, just { name: Salmon, value: 50.00, category: ouhdiuashd } is enough. Both the 1st option, as the 2nd option has as you list the products by category.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.