Is there a way to make a Firestore document field match the result of two others? I.e. field A + field B = field C

28 Views Asked by At

Is there a way to make a Firestore document field match the result of two others? I.e. field A + field B = field C

I will be using the Firestore database to store product information. Products are stored at different locations so there is an "inventory" object for each product that contains an object for each stock location. For example, product A might have the following field:

inventory: { london: 214, edinburgh: 100, cardiff: 342}

I would like to improve this so that it looks more like the below, where "total" updates itself to match the total of all the locations.

inventory: { total: 656, london: 214, edinburgh: 100, cardiff: 342}

How might this be achieved? The site has been built using react so I'm assuming I will need to build some kind of server using node and forever? I know this one is probably quite tricky but any help would be greatly appreciated. Thank you in advance.

1

There are 1 best solutions below

0
Frank van Puffelen On

There is no way to have Firestore automatically calculate the value of the total field. So that means this calculation will have to happen in your code, which can be done either in the client-side application code, or in a server-side - for example with Cloud Functions responding to each write of the inventory.

If you decide to go with client-side calculation for the total, you can use server-side security rules to ensure the value is correct as long as you can enumerate the keys in the document (so london, edinburgh and cardiff in your example).