【发布时间】:2020-07-21 07:11:54
【问题描述】:
我正在尝试更新我在 Firebase 数据库中的数据值,但是,每当我使用方法 .updateData(data) 时,它都会将现有数据覆盖到该数据中的任何内容。我使用过 FieldValue.increment() 但无济于事;它不断使我的应用程序崩溃(控制台显示与设备的连接丢失)。
我希望完成的是将“计数”字段 + 1 即可。但如前所述 FieldValue.increment() 使我的应用程序崩溃:(
数据格式如下:
{restaurantA: [{Count: 2, Item Name: Yummy Food, Location: Rowland Heights}]}
我的代码如下:
if (value.data.containsKey(restaurantName)) {
// Check if item is in here method below
value.data[restaurantName].forEach((itemElement) {
if (itemElement['Item Name'] == itemName) {
wishesDBRef.updateData({
// Error: This part replaces the existing values to the below
restaurantName: [
{
'Item Name': itemName,
'Count': itemElement['Count'] + 1,
'Location': restaurantLocation,
}
]
});
} else {
wishesDBRef.updateData({
restaurantName: FieldValue.arrayUnion([
{
'Item Name': itemName,
'Count': 1,
'Location': restaurantLocation,
}
]),
});
}
});
// Item is not in here add item in here method below
} else {
wishesDBRef.updateData({
restaurantName: [
{
'Item Name': itemName,
'Count': 1,
'Location': restaurantLocation,
}
]
});
}
现有代码将从以下位置更改值:
{restaurantA: [{Count: 2, Item Name: Yummy Food, Location: Rowland Heights}, {Count: 5, Item Name: delicious Food, Location: Rowland Heights}]}
收件人:
{restaurantA: [{Count: 3, Item Name: Yummy Food, Location: Rowland Heights}]}
我想要什么:
{restaurantA: [{Count: 3, Item Name: Yummy Food, Location: Rowland Heights}, {Count: 5, Item Name: delicious Food, Location: Rowland Heights}]}
不知道该怎么做,因为我一直在尝试各种方法。 提前感谢您的帮助。
编辑:也许它妨碍了我引用数据库的方式?
void uploadWish(String restaurantName, String itemName,
String restaurantLocation) async {
var wishesDBRef =
await dbReference.collection('Users').document('Wishes');
await wishesDBRef.get().then((value) {
// The above if-else statement here
}
【问题讨论】:
-
您可以使用
setData代替updateData并具有参数merge:true。 -
@ShubhamGupta 试过了,但仍然覆盖了我的值
标签: firebase flutter google-cloud-firestore