1

Sorry for the long title. Visually and more precise, I would like to update the stock value after a payment is made. However, I get stuck after querying the entire document (e.g. the selected one with title sneakers). Is there a way to actually query and update for example the Timberlands stock value to its value -1. Or do you have to get all data from the entire document. Then modify the desired part in javascript and update the entire document?

enter image description here

Here is a little snippet of a solution I came up with so far. However, this approach hurts my soul as it seems very inefficient.

const updateFirebaseStock = (orders) => {
  orders.forEach( async (order) => {
    try {
      collRef = db.doc(`collections/${order.collectionid}`);
      doc = await collRef.get();
      data = doc.data();
      //Here:const newItems = data.items.map(if it's corr name, update value, else just return object), results in desired new Array of objects.
      //Then Update entire document by collRef.update({items: newItems})
    } catch (error) {
      console.error(error)
    };
  });
}
adiga
  • 34,372
  • 9
  • 61
  • 83
Stino
  • 21
  • 2

1 Answers1

2

You don't need to get the document at all for that, all you have to do is use FieldValue.increment(), using your code as a starting point it could look like this:

collRef = db.doc(`collections/${order.collectionid}`);
collRef.update({
    Price: firebase.firestore.FieldValue.increment(-1)
});

You can increment/decrement with any numeric value using that function.

Ralemos
  • 5,571
  • 2
  • 9
  • 18