如何建模此结构以处理删除

问题描述 投票:1回答:1

我有一个名为lists的集合,它有ID代表列表ID的文档。这个文件有一个名为employees的集合,另一个名为locations

结构看起来像:

(lists)
    -listId
       (employees)
       (locations)

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

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

有什么建议?

android firebase google-cloud-firestore
1个回答
1
投票

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

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

如果您有更大的集合,则可能需要以较小批量删除文档以避免内存不足错误。重复此过程,直到删除整个集合或子集合。

即使Firebase团队没有推荐删除操作因为它是has negative security and performance implications,你仍然可以这样做,但仅限于小型集合。如果需要删除Web的整个集合,请仅从受信任的服务器环境中删除。

对于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();
}
© www.soinside.com 2019 - 2024. All rights reserved.