如何删除firebase集合文档,并删除所有子集合,并从认证中删除也使用Flutter?[重复]

1cosmwyk  于 2023-04-12  发布在  Flutter
关注(0)|答案(2)|浏览(126)

此问题已在此处有答案

How to get all of the collection ids from document on Firestore? [duplicate](1个答案)
昨天关门了。
我试图删除firebase收集文件,并与删除所有的子集合,并删除从认证也使用flutter。这里是我的数据库截图

我想删除用户文档与那些子集合(书籍和PDF)。
我的代码

void deleteUserDocument() async {
    final sp = context.watch<SignInProvider>();
    try {
      // Get the current user's ID
      final user = FirebaseAuth.instance.currentUser;
      final uid = user?.uid;
      if (uid != null) {
        // Get a reference to the user's document in Firestore
        final docRef = FirebaseFirestore.instance.collection("users").doc(uid);
        // Delete all subcollections in the user's document
        final collections = await FirebaseFirestore.instance.collection("users").doc(uid).listCollections();
        final batch = FirebaseFirestore.instance.batch();
        for (final collectionRef in collections) {
          final querySnapshot = await collectionRef.get();
          for (final docSnapshot in querySnapshot.docs) {
            batch.delete(docSnapshot.reference);
          }
          batch.delete(collectionRef);
        }
        await batch.commit();
        // Delete the user's document
        await docRef.delete();
        // Remove the user from Firebase Authentication
        await user?.delete();
        // Log the user out and navigate to the login screen
        sp.userSignOut();
        nextScreenReplace(context, const LoginScreen());
      }
    } catch (e) {
      // Handle any errors that occur during the deletion process
      print('Error deleting user document: $e');
      // Display an error message to the user
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Failed to delete account')),
      );
    }
  }

但在那里显示错误final collections = await FirebaseFirestore.instance.collection(“users”).doc(uid).listCollections();

错误截图

如何解决这个错误?

hivapdat

hivapdat1#

根据删除文档Firebase文档
警告:删除单据并不删除其子集合!
然后呢

不建议客户端删除收藏。

相反,您应该删除具有Delete data with a Callable Cloud Function子集合的文档,并从客户端应用程序调用它。
Firebase Docs还提供了一个示例firebase函数来删除文档,您可以在这里检查:解决方案:使用可调用的云函数删除数据

1bqhqjot

1bqhqjot2#

看来有两个问题需要你去解决。

  • 第一个,正如Rohit Kharche之前指出的,删除用户文档不会自动删除其子集合。因此,您需要遍历每个子集合的文档以删除它们。
  • 第二个问题与Firebase批处理有关,Firebase批处理限制为500个文档。如果子集合中的文档超过500个,则批处理操作将失败,删除过程将无法完成。

下面的代码解决方案解决了所有这些问题:

void deleteUser() async {
  final sp = context.watch<SignInProvider>();

  /* Since we are using batch to delete the documents usually the max batch size
  * is 500 documents.
  */
  const int maxBatchSize = 500;

  // Define the users collections;
  final List<String> collections = [
    "books",
    "pdfs",
  ];

  try {
    // Get the current user's ID
    final String? uid = FirebaseAuth.instance.currentUser?.uid;

    //loop through collection and delete each collection item from a user
    for (String collection in collections) {
      // Get the snapshot of a collection.
      final QuerySnapshot snapshot = await FirebaseFirestore.instance
          .collection('Users')
          .doc(uid)
          .collection(collection)
          .get();
      // Get the list of documents;
      final List<DocumentSnapshot> querySnapshotList = snapshot.docs;

      // Get the length of the list(no of documents in the collections)
      final int documentLengths = querySnapshotList.length;

      /* The below code allows us too loop through the documents and delete
      them after every 500 documents, since batch is full at 500.
       */
      final int loopLength = (documentLengths / maxBatchSize).ceil();
      for (int _ = 0; _ < loopLength; _++) {
        final int endRange = (querySnapshotList.length >= maxBatchSize)
            ? maxBatchSize
            : querySnapshotList.length;
        // Define the batch instance
        final WriteBatch batch = FirebaseFirestore.instance.batch();
        for (DocumentSnapshot doc in querySnapshotList.getRange(0, endRange)) {
          batch.delete(doc.reference);
        }
        // Commit the delete batch
        batch.commit();
        querySnapshotList.removeRange(0, endRange);
      }
    }
    // Delete the user profile
    await FirebaseFirestore.instance.collection('Users').doc(uid).delete();

    // Log out user from all platforms.
    sp.userSignOut();
    /*
    // Log out user from all platforms.
    Future.wait([
      _googleSignIn.signOut(),
      _facebookAuth.logOut(),
      _firebaseAuth.signOut(),
    ]);
     */
  } catch (e) {
    // Handle any errors that occur during the deletion process
    print('Error deleting user document: $e');
    // Display an error message to the user
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text('Failed to delete account')),
    );
  }
}

相关问题