本文介绍了有什么办法可以在FieldValue.arrayUnion中添加FieldValue.increment()吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个购物车应用.当用户单击同一产品时,我要增加编号.如果用户单击相同的项目10次,则我想这样更新Firestore.

I created a shopping cart app. When user clicks the same product I want to increment number.if the user clicks the same item 10 times, I want to update firestore like this.

项目:[{'productId':'1234','count':10},{'productId':'1111','count':1}]

因此,我决定使用 FieldValue.increment(1).但是将其添加到 arrayUnion

So, I decided to use FieldValue.increment(1). But I got an error when adding it inside 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);
  }

推荐答案

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

As the error clearly states, you can use FieldValue.increment() only when using set() and update() functions and not when using FieldValue.arrayUnion. You cannot add an element to an array and increment one of its elements at the same time. Besides that, FieldValue.increment() can only increment a property of type number which should exist distinct within a document and not as a member of an array.

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

If you need to increment the value of an array member, you should get that array on the client, get the desired element, update it and then write the document back.

如果有以下项目:

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

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

It is an object with two properties that exist within an array of objects, you cannot use FieldValue.increment(), to increment the count property of a single object. You cannot simply map that object into a custom object. Actually, you have in your document a list of HashMaps. So you need to write code for that, by iterating through the list, find the corresponding count property you want to increment, increment it and then write the document back.

这篇关于有什么办法可以在FieldValue.arrayUnion中添加FieldValue.increment()吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 21:34