I query the collection ".where" and get the document ID,And I want to delete it

Viewed 46

I wrote the following code. However, when I run it, it does not work. I am probably not able to get the document ID. sorry,Please let me know if there are any modifications to my code.

 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();
        }
      }
1 Answers

You have mixed up .then() and await patterns. Don't do this, it's confusing. In your case, you missed that the statment getting the ids is not done yet when you start deleteing. Pick one and stick with it. Personally, I think async/await makes for cleaner code:

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();
    }
  }
Related