gpt4 book ai didi

firebase - 有什么办法可以在FieldValue.arrayUnion中添加FieldValue.increment()?

转载 作者:行者123 更新时间:2023-12-03 03:36:58 27 4
gpt4 key购买 nike

我创建了一个购物车应用。当用户单击同一产品时,我要增加编号。
如果用户单击同一项目10次,则我想这样更新Firestore。
items:[{'productId':'1234','count':10},{'productId':'1111','count':1}]
因此,我决定使用FieldValue.increment(1)。但是在arrayUnion中添加它时出现错误

错误

Unhandled Exception: PlatformException(error, Invalid data. FieldValue.increment() can only be used with set() and update(), null)

代码
  Future<void> addToCart(ProductModel model){
var ref = _db.collection('cart').document('7iRLSvH5sgMjaBNw0V4E');

return ref.setData({
'userId':'1234',
'items':FieldValue.arrayUnion([{
'count':FieldValue.increment(1),
'productId':model.subCategoryId,
'productName':model.subCategoryName
}])
},merge: true);
}

最佳答案

Invalid data. FieldValue.increment() can only be used with set() and update(), null)



正如错误明确指出的那样,仅当使用 FieldValue.increment()set()函数时才可以使用 update(),而使用 FieldValue.arrayUnion时只能使用 而不是。您不能将元素添加到数组并同时增加其元素之一。除此之外, FieldValue.increment()只能增加应该在文档中存在的类型为number的属性,而 不能作为数组的成员存在

如果需要增加数组成员的值,则应在客户端上获取该数组,获取所需的元素,对其进行更新,然后将其写回。

编辑:

如果有以下项目:
[{'productId':'1234','count':10}]

这是一个在对象数组中存在两个属性的对象,您不能使用 FieldValue.increment()来增加单个对象的 count属性。您不能简单地将该对象映射到自定义对象。实际上,您的文档中有一个HashMaps列表。因此,您需要为此编写代码,方法是遍历列表,找到要增加的相应 count属性,将其增加,然后写回文档。

关于firebase - 有什么办法可以在FieldValue.arrayUnion中添加FieldValue.increment()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60301018/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com