Stino
Stino

Reputation: 21

Firebase Firestore: How to update or access and update a field value, in a map, in an array, in a document, that is in a collection

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)
    };
  });
}

Upvotes: 1

Views: 1757

Answers (1)

Rafael Lemos
Rafael Lemos

Reputation: 5829

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.

Upvotes: 2

Related Questions