首页 > 解决方案 > 如何在 Cloud Firestore 中的数组内增加地图中的值?

问题描述

添加数组:

    const buy =  (e) => {
    const washingtonRef = firebase.firestore().collection("users").doc(props.uid)
    washingtonRef.update({
        orders: firebase.firestore.FieldValue.arrayUnion({ id: e.target.name, quantity: +1 })
    });
}

删除数组:

    const delPr = (e) => {
    const washingtonRef = firebase.firestore().collection("users").doc(props.uid)
    washingtonRef.update({
        orders: firebase.firestore.FieldValue.arrayRemove({ id: e.target.name, quantity: +1 })
    });
}

在此处输入图像描述

是否可以以某种方式更改数量字段?

标签: reactjsgoogle-cloud-firestore

解决方案


更新

您可以对 map 使用 increment 方法,但不能将其用于数组,因为无法将数组元素调用为命名字段值。

另一种方法是读取整个文档,修改内存中的数据并将字段更新回文档,例如nodejs

function IncrementArray(myDoc) {
  let docData = _.cloneDeep(myDoc.data())
  docData.orders[0].quantity += 1
  docData.orders[1].quantity += 1
  return docData
}

firestore.collection('users').doc(doc.id).update(
  IncrementArray(doc)
)

参考:

  1. https://stackoverflow.com/a/58310449/8753991
  2. https://stackoverflow.com/a/66366708/8753991

推荐阅读