[英]How can I delete a document with all its subcollections in firebase with flutter and dart
Every time I try to delete a document programmatically using documentSnapshot.delete(), the firebase only deletes the document and not its subcollections.每次我尝试使用 documentSnapshot.delete() 以编程方式删除文档时,firebase 仅删除文档而不删除其子集合。 I want to permanently delete a document and all its subcollections with the push of a button and every time the user tries to create the same document, it'd be empty.
我想通过按下按钮永久删除一个文档及其所有子集合,每次用户尝试创建相同的文档时,它都是空的。
What's the proper way to do that?这样做的正确方法是什么?
(CLOSED) (关闭)
This is the code that worked for me:这是对我有用的代码:
CollectionReference<Map<String, dynamic>> collectionReference = FirebaseFirestore.instance.collection('collection name').doc('document name').collection('collection name');
DocumentReference<Map<String, dynamic>> documentReference = collectionReference.doc('document name');
documentReference.collection('lists').get().then((lists) {
lists.docs.forEach((listElement) {
documentReference.collection('lists').doc(listElement.id.toString()).collection('cards').get().then((cards) {
cards.docs.forEach((cardElement) {
documentReference.collection('lists').doc(listElement.id.toString()).collection('cards').doc(cardElement.id.toString()).delete();
});
});
documentReference.collection('lists').doc(listElement.id.toString()).delete();
});
});
await documentReference.delete();
Deleting a
document
does not automatically delete all documents in its sub-collections.删除
document
不会自动删除其子集合中的所有文档。
There is no method in firestore API to delete subcollections along with the document. Firestore API 中没有方法可以随文档一起删除子集合。 You need to loop through and delete the documents in subcollections and then delete the parent
document
.您需要遍历并删除子集合中的文档,然后删除父
document
。
I don't know Dart but here's my simple solution with PHP Firestore;我不知道 Dart 但这是我使用 PHP Firestore 的简单解决方案;
public function destroyCollection(CollectionReference $collection)
{
$documents = [];
foreach ($collection->listDocuments() as $document) {
$documents[] = $document;
}
$this->destroyDocuments($documents);
}
/**
* @param DocumentReference[] $documents
*/
public function destroyDocuments(array $documents)
{
if (!$documents) return;
$batch = $this->database->getBatch();
foreach ($documents as $document) {
$batch->delete($document);
foreach ($document->collections() as $collection) {
$this->destroyCollection($collection);
}
}
$batch->commit();
}
It'll delete all the documents that it finds no matter how deeply nested they are.它会删除它找到的所有文档,无论它们的嵌套有多深。 And non-existing docs won't show up in snapshots and queries so that's why I'm using the
listDocuments()
method even tho I'm sacrificing performance a bit.并且不存在的文档不会出现在快照和查询中,所以这就是我使用
listDocuments()
方法的原因,即使我牺牲了一点性能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.