hkrlys
hkrlys

Reputation: 441

Using arrays or sub collections?

Having this structure for example:

Businesses       (collection)
   business1     (doc)
   business2
   business3
       info            (object)
            location:
            earnings:
       products:       (object  or collection?)
            product1
            product2
            product3   (object)
                name:yy
                price:xx
                likes:3

I am creating a businesses collection, where every document is a business, and inside abusiness doc I will have 2 objects - info and products.

I will need to be able to:

  1. Read a business including everything (all products) based on business or product name
  2. Add a new product to a business

If i use a sub-collection called products for every business, i will not be able to read in one shot the info and the products (all data for a specific business name).

If i use an array of objects called products (inside a business doc), I will not be able to query for a business doc, based on a product name.

Is this even possible to achieve ?

Upvotes: 0

Views: 169

Answers (1)

Joshua de Guzman
Joshua de Guzman

Reputation: 2143

If i use a sub-collection called products for every business, i will not be able to read in one shot the info and the products (all data for a specific business name).

With Firestore, you cannot query from a top level and other collections in a single query.

If i use an array of objects called products (inside a business doc), I will not be able to query for a business doc, based on a product name.

Since Firestore is a NoSQL database, JOIN in queries is not available. If you opt in to use arrays over sub collections, which I recommended based on the complexity of your needs, you may have to do another manual query per item, if deemed necessary (eg. displaying list of products with the appropriate business name or searching business via product name).

Option 1. If you want a product be exclusive to one business, you can do something like this:

businesses (collection)
- business (object)
-- id (object identifier)

products
- product
-- id
-- business_id (reference to the business)

Option 2. If you want a product be used by other businesses, you can do something like this:

businesses (collection)
- business (object)
-- id (object identifier)

products
- product
-- id

businesses_products
- business_product
-- id
-- business_id
-- product_id

Usage

Assuming that you chose Option 1, searching will be something like this:

Steps

  1. Search for product
  2. Run a query in the products collection
  3. Retrieve the business_id based from the result
  4. Run another query in the business collection

Further reading

Upvotes: 2

Related Questions