[英]How delete a collection or subcollection from Firestore?
我有一個名為列表的集合,它包含 ID 代表列表 ID 的文檔。 該文檔有一個名為employees
的集合和另一個名為locations
的集合。
結構如下所示:
(lists)
-listId
(employees)
(locations)
如果用戶想要刪除特定列表,那么問題是我們無法刪除 listId,因為這將保留集合(如 Firestore 文檔所述)。
如何對結構進行建模以滿足需求? 我似乎無法繞過子集合的需要。
有什么推薦嗎?
無需為了刪除某些集合而重構數據庫。 要刪除 Cloud Firestore 中的整個集合或子集合,請檢索集合或子集合中的所有文檔並將其刪除。 因此,要刪除特定列表,請使用以下步驟:
employees
集合下的所有文檔並刪除它們locations
集合下的所有文檔並刪除它們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.