Each product may have variations of sizes and each with its different colors and quantities.
Example:
Product Name: Shirt
Size: Large
Color: Red, Qty: 10
Color: Blue, Qty: 5
Product Name: Cupp
Size: Large
Color: Red, Qty: 10
Color: Blue, Qty: 5
The way I submitted it and what shows in the console:
Code: Link: https://codesandbox.io/s/form-order-working-4f6g2
Firestore:
Firestore doesn't have the ability to update an existing element in an indexed array. It supports only two methods, arrayUnion() to add an element and arrayRemove() to remove an element from the array as mentioned in the documentation.
As an alternative, you can read the entire array out of the document, make modifications to it in memory, then update the modified array field entirely. This is an error prone and tedious process. You can have a look at this article to know more about it.
I am not sure of your use case, but it seems you can make your database structure more suitable by using maps(nested objects) instead of arrays. Something like this -
By doing this you can update the nested objects by dot notation as mentioned here. Some sample to update the document will look like this -
async function updateData(color) {
const docRef = doc(db, 'collectionId', 'documentId');
await updateDoc(docRef,{
[`colorStockList.${color}`]:300
});
}
UPDATE
To update the stocks automatically you can implement a method which will get invoked when an order is placed. Within that method you can use the increment() method as described here. The increment() method can increase or decrease the stocks based on the value provided by you. For example if someone places an order for 3 shirts you can pass that number to the increment() method so that it can decrease the stocks by that value. Make sure to use -ve sign with the value when you want to decrease the stocks.
The method should look something like this -
async function updateData(color,value) {
const docRef = doc(db, 'collectionId', 'documentId');
await updateDoc(docRef,{
[`colorStockList.${color}`]:increment(-value)
});
}