1

I have a question about firestore and cloud function.

let say i have 2 collection: products and reuse_shopping_carts.

and my reuse_shopping_cart document contain many products with all it’s properties (id,name,price,href).

now i want that if i change the price of a specific product in products collection , a cloud function will run on all reuse_shopping_cart documents and in every document that contains the specific product it will change is price.

someone can explain me how? or what is the right approach to do it?

i know i can store in the reuse_shopping_cart only the product id and fetch the updated product data at client, but for a list of 100 product in one reuse_shopping_cart it’s will require 100 separate query for every time i want to read the shopping list, and changing price of a product is mach more rare, so i think it’s a better approach.

if you think differently i will happy to hear... thank you!

Haim Cohen
  • 11
  • 4
  • If price changes are less common than reads of shopping carts, then your duplication of the price into the shopping cart will save you on IO operations. In fact, I'm not even sure you should update the price in all shopping carts, since the price may have been determined when the user added the item to the cart. For all options, see my answer here: https://stackoverflow.com/questions/30693785/how-to-write-denormalized-data-in-firebase – Frank van Puffelen Jan 03 '19 at 14:22
  • Hi Frank, in normal shopping cart you right, but this is reuse shopping cart that stay forever for the user and it's a start point for a new shopping cart so the price need to be changeable over time. i read about "Transactions and batched writes" in the firebase doc but it's limited to a maximum of 500 documents... so it's a problem because after some time i will have more the 500 reuse shopping list. any advice? – Haim Cohen Jan 03 '19 at 15:40
  • Ah OK. In that case it makes sense. The options in my linked answer remain the same, and your approach of updating them from Cloud Functions sounds valid to me. – Frank van Puffelen Jan 03 '19 at 15:43

1 Answers1

0

You can structure your reuse_shopping_carts document like this:

products: (map)   
  (product id)
    name:
    value:

For example:

Example document

Then to find which documents to update when the price changes you can query like this:

firebase.firestore().collection('reuse_shopping_carts').where(`products.${productId}.price`, '>=', 0)
Ricardo Smania
  • 2,939
  • 2
  • 26
  • 35