【问题标题】:How to delete multiple documents with specific Value in Firestore with Flutter如何使用 Flutter 在 Firestore 中删除具有特定值的多个文档
【发布时间】:2020-11-20 01:20:02
【问题描述】:

我正在尝试从我的集合中删除一个字段中具有特定字符串值的多个文档。 但我认为我做错了什么。

onPressed: () async {
  Firestore.instance.collection('collection').getDocuments().then((snapshot) {
  for (DocumentSnapshot ds in snapshot.documents.where(('field') == 'specificValue'){
    ds.reference.delete();
    });
  });
}

我目前正在尝试在获取所有文档后使用循环删除每个项目,但我无法删除特定项目。因为我在“where”部分下遇到错误。

【问题讨论】:

    标签: database firebase flutter delete-file


    【解决方案1】:

    要使用where,您需要获取该collection 中所有文档的列表,然后获取where 以过滤List 并删除filteredList

      onPressed: () async {
        onPressed() async {
        Firestore.instance.collection('collection').getDocuments().then((snapshot) {
          List<DocumentSnapshot> allDocs = snapshot.documents;
          List<DocumentSnapshot> filteredDocs =  allDocs.where(
                  (document) => document.data['field'] == 'specificValue'
          ).toList();
          for (DocumentSnapshot ds in filteredDocs){
            ds.reference.updateData({
              'field': 'newValue'
            });
          }
        });
      }
    

    【讨论】:

    • 嘿,你的功能很好用。但我注意到最好将每个文档的“归档”值设置为空,而不是删除它们。是否可以使用 updateData() 函数而不是 delete() 函数来做到这一点?如果是,我怎么能只更新这个字段值。
    • 哦,'归档'是一种类型。它的意思是“字段”
    猜你喜欢
    • 2021-10-21
    • 2020-11-21
    • 2020-10-05
    • 2021-01-07
    • 1970-01-01
    • 2019-04-04
    • 1970-01-01
    • 1970-01-01
    • 2018-06-18
    相关资源
    最近更新 更多