[英]Flutter Firebase firestore append data with unique ID
I'm working on the Flutter app where users can save multiple addresses.我正在开发 Flutter 应用程序,用户可以在其中保存多个地址。 Previously I used a real-time database and it was easier for me to push data in any child with a unique Id but for some reason, I changed to Firestore and the same thing want to achieve with firestore.
以前我使用实时数据库,我更容易将数据推送到具有唯一 ID 的任何孩子中,但由于某种原因,我改为使用 Firestore,并且希望通过 Firestore 实现相同的目标。 So, I generated UUID to create unique ID to append to
user_address
因此,我生成了 UUID 来创建唯一 ID 以附加到
user_address
This is how I want这就是我想要的
and user_address looks like this和 user_address 看起来像这样
And this is how it's getting saved in firestore这就是它在火库中的保存方式
So my question Is how I append data with unique id do I have to create a collection inside users
field or the above is possible?所以我的问题是我如何附加具有唯一 ID 的数据我必须在
users
字段内创建一个集合还是上述可能?
Below is my code I tried to set
and update
even user FieldValue.arrayUnion(userServiceAddress)
but not getting the desired result下面是我尝试
set
和update
用户FieldValue.arrayUnion(userServiceAddress)
但没有得到所需结果的代码
var uuid = Uuid();
var fireStoreUserRef =
await FirebaseFirestore.instance.collection('users').doc(id);
Map locationMap = {
'latitude': myPosition.latitude,
'longitude': myPosition.longitude,
};
var userServiceAddress = <String, dynamic>{
uuid.v4(): {
'complete_address': completedAddressController.text,
'floor_option': floorController.text,
'how_to_reach': howtoreachController.text,
'location_type': locationTag,
'saved_date': DateTime.now().toString(),
'user_geo_location': locationMap,
'placeId': addressId
}
};
await fireStoreUserRef.update({'user_address': userServiceAddress});
If I use set
and update
then whole data is replaced with new value it's not appending, so creating a collection is the only solution here and If I create a collection then is there any issue I'll face?如果我使用
set
和update
则整个数据将被替换为未附加的新值,因此创建一个集合是这里唯一的解决方案,如果我创建一个集合,那么我会遇到什么问题吗?
You won't have any issues per se by storing addresses in a separate collection with a one-to-many relationship, but depending on your usage, you may see much higher read/write requests with this approach.通过将地址存储在具有一对多关系的单独集合中,您本身不会有任何问题,但根据您的使用情况,您可能会看到使用这种方法更高的读/写请求。 This can make exceeding your budget far more likely.
这会使超出预算的可能性大大增加。
Fortunately, Firestore allows updating fields in nested objects via dot notation.幸运的是,Firestore 允许通过点符号更新嵌套对象中的字段。 Try this:
尝试这个:
var userServiceAddress = {
'complete_address': completedAddressController.text,
'floor_option': floorController.text,
'how_to_reach': howtoreachController.text,
'location_type': locationTag,
'saved_date': DateTime.now().toString(),
'user_geo_location': locationMap,
'placeId': addressId
};
await fireStoreUserRef.update({'user_address.${uuid.v4()}': userServiceAddress});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.