简体   繁体   English

Firebase Firestore:如何更新或访问和更新 map、数组、文档、集合中的字段值

[英]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.有没有办法实际查询和更新例如 Timberlands 股票价值到它的价值 -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?然后修改javascript中想要的部分,更新整个文档?

在此处输入图像描述

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:您根本不需要为此获取文档,您所要做的就是使用FieldValue.increment() ,使用您的代码作为起点,它可能如下所示:

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.您可以使用 function 对任何数值进行递增/递减。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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