Here's my data structure, how it is organized (firebase database):
-database
-productsList
-item1: 0
-item2: 0
-item3: 0
-item4: 0
-orders
-order1:
-...
-order2:
-...
-...
I'm building a shopping app that has a list of products. Customers can choose what they want to buy and make an order. When they do the product's quantities would increase based on what they've chosen. Say a customer chose to buy 2 units of item2 e 5 units of item4, when one sends a request it will write at a different location with the following data like so:
-orders
-orderKey
-items
-item2: 2
-item4: 5
Then, the list would update to (based on onCreate method):
-productsList
-item1: 0
-item2: 2
-item3: 0
-item4: 5
But, let's suppose another customer did a request at the same time, the product list must acknowledge that.
I'm well aware of the firebase transactions, and this must be implemented as a transaction rather than an update. However, all the examples that a thoroughly searched here only show how to update a single node and not multiple children.
I'm using cloud functions to accomplish that, that means I'm using typescript.
What would be the best approach to update multiple children using a transaction?
How would be possible to only get and increment only the desirable nodes?
Please, any help would be much appreciated.
EDIT: After Frank van Puffelen answer my question I decided to make it more clear to explain exactly what I need to do.
I wish only to update one node named productsList and, in this example, its child nodes item2 and child4.
Here's some code to illustrate it better:
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
admin.initializeApp(functions.config().firebase)
export const onOrderCreate = functions.database
.ref('/orders/{oid}')
.onCreate(async (snapshot, context) => {
const orderId = context.params.oid
console.log(`new order made: ${oid}`)
const orderData = snapshot.val()
const items = getProductsAndQuantities(orderData)
const path = 'productsList'
return admin.database().ref(path).transaction(items => {
// I would like to know if there's a way to update only the bought items, like
const updatedList = {
'item2': item2oldValue + 2,
'item4': item2oldValue + 5
}
return updatedList
})
})
// Get the order data and return only the items and its quantities
function getProductsAndQuantities(data: any): Object {
// Return items, exemple
const products = {
'item2': 2,
'item4': 5
}
return products
}