【问题标题】:how to add or remove item to the the existing array in firestore ?如何在 firestore 中的现有数组中添加或删除项目?
【发布时间】:2019-02-08 13:23:07
【问题描述】:

Firestore 最近添加了新的新方法 FieldValue.arrayUnion(value) 和 FieldValue.arrayRemove(value) 但我在 flutter cloud_firestore 包中找不到实现。有没有办法达到这个结果?

Firestore 添加更新:https://firebase.google.com/docs/firestore/manage-data/add-data#update_elements_in_an_array

【问题讨论】:

    标签: dart flutter google-cloud-firestore


    【解决方案1】:

    这里是显示如何更新数组值的简单示例。我的文档有一个 up voters 数组来添加对文档投票的用户 ID。

    配置 firestore,配置详情可以从您的 google-services.json 文件中复制

       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'])
                  });
                }
              });
    

    希望对你有帮助

    【讨论】:

      【解决方案2】:

      更新: 现在看来它是支持的!使用版本 0.8.0。

      https://pub.dartlang.org/packages/cloud_firestore

      然后使用 FieldValue.arrayUnion 和 FieldVale.arrayRemove。


      目前似乎没有办法。请关注以下两个github问题:

      https://github.com/flutter/flutter/issues/21148 https://github.com/flutter/flutter/issues/20688

      【讨论】:

        猜你喜欢
        • 2021-10-03
        • 2021-03-04
        • 2014-05-05
        • 2013-04-03
        • 2019-10-13
        • 1970-01-01
        • 2019-06-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多