简体   繁体   中英

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 (eg 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?

在此处输入图像描述

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM