【问题标题】:updating Map values in array flutter Firebase更新数组颤动Firebase中的地图值
【发布时间】:2022-02-13 21:23:02
【问题描述】:

这是地图和我正在尝试更新的 vlaue

问题是当我尝试更新 imageUrl 时,整个 Map 只替换为 ImageUrl 新值 像这样

我想要的只是更新 imageUrl,不影响其他数据

这是我做的,但不是工作

FirebaseFirestore.instance.collection('oorders').doc('MyDocId')
                                 .update({ 'items.0.imageUrl'    :  'new image Url' });

【问题讨论】:

标签: flutter google-cloud-firestore


【解决方案1】:

从提供的 Firestore 数据库结构可以清楚地看出,您正在尝试更新 Firestore 文档中数组字段内的元素。但目前 Firestore 无法更新索引数组中的现有元素。它只支持两种方法,arrayUnion() 添加元素和arrayRemove() 从数组中删除元素,如documentation 中所述。

因此,如果您尝试执行以下操作 -

FirebaseFirestore.instance
    .collection('oorders')
    .doc('MyDocId')
    .update({'items.0.imageUrl': 'new image Url'});

它将删除数组元素items,并使用更新语句中提到的字段创建另一个名为items的映射。

作为替代方案,您可以从文档中读取整个数组,在内存中对其进行修改,然后完全更新修改后的数组字段。这是一个容易出错且乏味的过程。您可以查看此article 以了解更多信息。

我不确定您的用例,但您似乎可以通过使用映射(嵌套对象)而不是数组来使您的数据库结构更合适。像这样 -

通过这样做,您可以通过here 提到的点表示法更新嵌套对象,这将只更新提到的字段而不删除其他字段。更新文档的示例将如下所示 -

   var item = 'item1';
   var propertyToBeUpdated = 'imageUrl';
   var newImageUrl = 'New image Url';
   FirebaseFirestore.instance
       .collection('collectionId')
       .doc('documentId')
       .update({'items.$item.$propertyToBeUpdated': newImageUrl});

【讨论】:

  • _ 在内存中对其进行修改,然后完全更新修改后的数组字段。_ 这是做降神会,但我真的很关心 firebase 读写限制,所以我试图用 .更新为不使用额外数据顺便说一句这是我发布项目'List> selectedImages = [];'的乐趣firebaseFirestore .collection('Orders') .doc(orderId) .set({ 'id': orderId, 'items': selectedImages,}) 我该怎么做你上面提到的结构
  • 这似乎与原来的问题不同。我建议您为此发布一个新问题。
猜你喜欢
  • 2021-04-07
  • 2020-08-12
  • 2020-10-28
  • 1970-01-01
  • 2021-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-16
相关资源
最近更新 更多