我查询集合".where"获取文档ID,然后我想删除它



我编写了以下代码。但是,当我运行它时,它不起作用。我可能无法获得文件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();
}
}

您混淆了.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();
}
}

相关内容

最新更新