【问题标题】:How to increment a value in a map inside an array in Cloud Firestore?如何在 Cloud Firestore 中的数组内增加地图中的值?
【发布时间】:2021-05-28 01:49:30
【问题描述】:

添加数组:

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

enter image description here

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

【问题讨论】:

  • “如果你需要增加一个数组成员的值,你应该在客户端获取那个数组,获取想要的元素,更新它然后写回文档”见stackoverflow.com/a/60301382/3959488跨度>
  • 所以我必须完全重写整个对象数组?
  • 以 JSON 格式保存对象会更容易吗?
  • 是的,如果你把它用作地图(就像你说的,一个 JSON 对象),那么你可以使用increment 方法。另一方面,您将无法再使用 arrayUnionarrayRemove 方法,因为它们只适用于数组,正如其名称所示。

标签: reactjs google-cloud-firestore


【解决方案1】:

更新

您可以对 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

【讨论】:

  • 订单 - 是数组
  • 它不起作用 --- 'orders[0].quantity': firebase.firestore.FieldValue.increment(1),
  • 所以我必须完全重写整个数组吗?
  • @YuraProstyk 是的
猜你喜欢
  • 2020-02-06
  • 1970-01-01
  • 2021-12-10
  • 1970-01-01
  • 2018-11-18
  • 1970-01-01
  • 2019-09-03
  • 2020-11-08
  • 2013-04-06
相关资源
最近更新 更多