如何在Firestore中的现有阵列中添加或删除项目? [英] how to add or remove item to the the existing array in firestore ?

查看:57
本文介绍了如何在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆