繁体   English   中英

如何从 Firestore 中删除集合或子集合?

[英]How delete a collection or subcollection from Firestore?

我有一个名为列表的集合,它包含 ID 代表列表 ID 的文档。 该文档有一个名为employees的集合和另一个名为locations的集合。

结构如下所示:

(lists)
    -listId
       (employees)
       (locations)

如果用户想要删除特定列表,那么问题是我们无法删除 listId,因为这将保留集合(如 Firestore 文档所述)。

如何对结构进行建模以满足需求? 我似乎无法绕过子集合的需要。

有什么推荐吗?

无需为了删除某些集合而重构数据库。 要删除 Cloud Firestore 中的整个集合或子集合,请检索集合或子集合中的所有文档并将其删除。 因此,要删除特定列表,请使用以下步骤:

  1. 查找employees集合下的所有文档并删除它们
  2. 查找locations集合下的所有文档并删除它们
  3. 删除listId文档

如果您有较大的集合,您可能希望以较小的批次删除文档以避免内存不足错误。 重复该过程,直到您删除了整个集合或子集合。

即使 Firebase 团队不推荐删除操作,因为它对has negative security and performance implications ,您仍然可以这样做,但仅限于小型集合。 如果您需要删除整个网络收藏,请仅从受信任的服务器环境中执行此操作。

对于 Android,您可以使用以下代码:

private void deleteCollection(final CollectionReference collection, Executor executor) {
    Tasks.call(executor, () -> {
        int batchSize = 10;
        Query query = collection.orderBy(FieldPath.documentId()).limit(batchSize);
        List<DocumentSnapshot> deleted = deleteQueryBatch(query);

        while (deleted.size() >= batchSize) {
            DocumentSnapshot last = deleted.get(deleted.size() - 1);
            query = collection.orderBy(FieldPath.documentId()).startAfter(last.getId()).limit(batchSize);

            deleted = deleteQueryBatch(query);
        }

        return null;
    });
}

@WorkerThread
private List<DocumentSnapshot> deleteQueryBatch(final Query query) throws Exception {
    QuerySnapshot querySnapshot = Tasks.await(query.get());

    WriteBatch batch = query.getFirestore().batch();
    for (DocumentSnapshot snapshot : querySnapshot) {
        batch.delete(snapshot.getReference());
    }
    Tasks.await(batch.commit());

    return querySnapshot.getDocuments();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM