android - 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
解决方案
从上面的代码中,下面的行有问题:
'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()
})
推荐阅读
- python - 如何访问 Pandas DataFrame 中的标称值和不确定性?
- reactjs - 页面中没有加载css background-images,反应
- swift - 实现 UIPageViewController 的问题
- templates - Terraform k8sraw 提供程序错误:产生了一个意外的新值,但在创建模板时现在不存在
- validation - 如何验证相互依赖的文本框并在动态(使用 JS)添加的输入文本框下显示错误消息?
- r - 基于R中不同数据框中的另一列选择列
- python - 使用具有每日平均值的特定字符串列创建新数据集
- kubernetes - 在 Kubernetes 节点中“共享”静态 IP
- php - 如何在PHP中链接文件夹中的图像
- python - 用图像替换 x 标签