【问题标题】:I query the collection ".where" and get the document ID,And I want to delete it我查询集合“.where”并获取文档 ID,我想删除它
【发布时间】:2021-10-28 22:16:24
【问题描述】:

我写了以下代码。 但是,当我运行它时,它不起作用。 我可能无法获得文档 ID。 抱歉,如果我的代码有任何修改,请告诉我。

 Future<void> deleteRoom() async {

//Put the ID of the document to be deleted in the list
        List deleteRoomIdList = []; 

//The ID of the document to be deleted is placed here in a for statement.
        String deleteId;

    
        FirebaseFirestore.instance
            .collection('room')
            .where('roomCount', whereIn: [0, null])
            .get()
            .then((QuerySnapshot querySnapshot) => {
                  querySnapshot.docs.forEach(
                    (doc) {
                      deleteRoomIdList.add(doc.id);
                    },
                  ),
                });

    //Deleting with a for statement
        for (deleteId in deleteRoomIdList) {
          await FirebaseFirestore.instance
              .collection('room')
              .doc(deleteId)
              .delete();
        }
      }

【问题讨论】:

  • 请澄清您的具体问题或提供其他详细信息以准确突出您的需求。正如目前所写的那样,很难准确地说出你在问什么。

标签: firebase flutter dart google-cloud-firestore


【解决方案1】:

您混淆了.then()await 模式。不要这样做,这很混乱。就您而言,当您开始删除时,您错过了获取 id 的语句尚未完成。选择一个并坚持下去。就个人而言,我认为 async/await 可以使代码更简洁:

Future<void> deleteRoom() async {
    final deleteRoomIdList = []; 

    final querySnapshot = await FirebaseFirestore.instance
        .collection('room')
        .where('roomCount', whereIn: [0, null])
        .get();

    querySnapshot.docs.forEach((doc) { deleteRoomIdList.add(doc.id); });

    for (final deleteId in deleteRoomIdList) {
      await FirebaseFirestore.instance
          .collection('room')
          .doc(deleteId)
          .delete();
    }
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-07-11
    • 2021-06-11
    • 2011-06-12
    • 2023-04-02
    • 2019-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多