如何向firestore中的现有数组添加或删除项目? [英] how to add or remove item to the the existing array in firestore ?
问题描述
Firestore 最近添加了新方法 FieldValue.arrayUnion(value) 和 FieldValue.arrayRemove(value) 但我在 flutter cloud_firestore 包中找不到实现.有什么办法可以达到这个结果吗?
Firestore has recently add the new new method FieldValue.arrayUnion(value) and FieldValue.arrayRemove(value) but i couldn't find the implementation in flutter cloud_firestore package. Is there any way to achieve this result ?
Firestore addUpdate:https://firebase.google.com/docs/firestore/manage-data/add-data#update_elements_in_an_array
Firestore addUpdate: https://firebase.google.com/docs/firestore/manage-data/add-data#update_elements_in_an_array
推荐答案
这里是一个简单的例子,展示了如何更新数组值.我的文档有一个投票者数组,用于添加对文档进行投票的用户 ID.
Here is the simple example to show how to update the array values. My document have an up voters array to add the user id's who have up-votes the document.
配置 firestore,可以从您的 google-services.json 文件中复制配置详细信息
configure firestore, the config details can be copied form your google-services.json file
final FirebaseApp app = await FirebaseApp.configure(
name: 'test',
options: const FirebaseOptions(
projectID: 'projid',
googleAppID: 'appid',
apiKey: 'api',
databaseURL: 'your url',
),
);
final Firestore firestore = Firestore(app: app);
await firestore.settings(timestampsInSnapshotsEnabled: true);
使用交易更新代码
fireStore.runTransaction((Transaction tx) async {
DocumentSnapshot snapshot =
await tx.get(widget._document.reference);
var doc = snapshot.data;
if (doc['upvoters'].contains('12345')) {
await tx.update(snapshot.reference, <String, dynamic>{
'upvoters': FieldValue.arrayRemove(['12345'])
});
} else {
await tx.update(snapshot.reference, <String, dynamic>{
'upvoters': FieldValue.arrayUnion(['12345'])
});
}
});
希望能帮到你
这篇关于如何向firestore中的现有数组添加或删除项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!