首页 > 解决方案 > Firestore - 添加对象数组

问题描述

我在将对象数组(表)添加到对象数组(餐厅)时遇到了麻烦。我的意思是,我有以下 Firestore 结构:

... (other data)
restaurants: [
   0: {
      name: name_0
      ...
      tables: [
          0: { no_chairs: 5, ... },
      ]
   },
   ...
]

我知道如何向餐馆添加新对象,但如果表列表包含任何数据,我在添加新餐馆时遇到问题。

我的代码 rn:

    var collection = firestore.collection('usersData')
        .doc(this.currentUser.uid).collection('buisness').doc('restaurants');
    collection.update({
      'restaurants': FieldValue.arrayUnion([restaurant.toJson()]),
    }).then( ... // reaction based on api answer
class Restaurant:
     Map<String, dynamic> toJson() => {
    'name': name,
    ...
    'tables': tables!=null? [tables] : [], // I think that I should modify this line
  };

class Table:
    Map<String, dynamic> toJson()=> { // Or this method / use another
    'no_chairs': no_chairs,
    ...
  };

有什么简单的方法吗?最好不要修改firestore文件结构,但如果有必要我愿意这样做。


额外问题:如何修改表列表中的对象?例如我想将 no_chairs 更改为 7

标签: androidfirebaseflutter

解决方案


从上面的代码中,下面的行有问题:

'tables': tables!=null? [tables] : [], 

这部分[tables]意味着您将列表tables作为外部列表的一个元素。

为了说明,iftables如下所示:

List<int> tables = [1, 2, 3];

那么,[tables]是不是这样的:

[[1, 2, 3]]

解决方案

tables由于您正在发送列表,因此您可以直接使用该变量。

在发送您的tables对象之前,您需要将其转换为当前列表中的地图列表TableModel(根据您在下面的评论)。

因此,您可以将代码修改为:

'tables': tables != null ? tables.map((TableModel table) => table.toJson()).toList() : [], 

额外问题:如何修改表列表中的对象?例如我想将 no_chairs 更改为 7

解决方案:您必须获取实际的餐馆列表并修改您想要的确切表对象并将修改后的列表设置为 Firestore。

 var collection = firestore.collection('usersData').doc(this.currentUser.uid).collection('buisness').doc('restaurants');

 //Get list of restaurants
 List<Restaurant> restaurantList = ((await collection.get()).data()).map((dynamic restaurantJson) => Restaurant.fromJson(restaurantJson)).toList();

 Set number of chairs
 //
 restaurantList[restaurantIndex].tables[tableIndex].no_chairs = 7; //This assumes the no_chairs field is not final

 //Set list 
 collection.set({
   "restaurants": restaurantList.toJson()
 })


推荐阅读