有没有办法在FieldValue.arrayUnion中添加FieldValue.increment()



我创建了一个购物车应用程序。当用户点击相同的产品时,我想增加数量。如果用户点击同一个项目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);
}

无效数据。FieldValue.increment((只能与set((和update((一起使用,null(

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

如果您需要增加数组成员的值,您应该在客户端上获取该数组,获取所需的元素,更新它,然后写回文档。

编辑:

如果以下项目:

[{'productId':'1234','count':10}]

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

最新更新