获取firestore中已删除文档的ID



我有一个包含数千个文档的大集合。这些文档具有包含文档的子集合。现在我删除了很多最高级别的文件。

结构:MyCollection => MyDocument => MySubcollection => MySubdocument

现在我意识到,文件被删除了(没有显示在任何查询中(,但子集合及其文档仍然存在。现在我不知道如何删除它们,因为我不知道被删除文档的ID。

当我试图通过向我的收藏发送一个查询来读取所有文档来查找ID时,删除的文档(按设计(不再包括在内。那么,我现在如何计算他们的ID来删除他们的子集合呢?

谢谢你的建议!

这一切都取决于你的确切目标

如果您想删除MyCollection集合中的ALL文档,包括子集合中ALL的文档,可以使用Firebase CLI和以下命令:

firebase firestore:delete MyCollection -r

执行firebase firestore:delete --help以获取更多选项。

当然,这只能由Firebase项目的所有者来完成。


如果您想允许其他用户从前端做同样的事情(即所有文档,包括所有子集合(,您可以使用";用可调用的云函数删除数据";部分。

如本文档所述:

您可以利用Firebase命令行界面(CLI(中的firestore:delete命令。您可以使用firebase-tools软件包将Firebase CLI的任何功能导入Node.js应用程序。

Firebase CLI使用Cloud Firestore REST API查找指定路径下的所有文档并将其单独删除。这种实现不需要知道你的应用程序的特定数据层次结构,甚至会发现并删除";孤儿;不再具有父级的文档。


如果您只想删除MyCollection集合中文档的子集以及子集合中的文档,您可以使用与上述相同的方法,使用文档路径,例如:

firestore:delete MyCollection/MyDocument -r

最后,如果您的问题是您已经删除了";"父";如果您不知道如何删除(孤立(子集合中的文档(因为您不知道父集合的ID(,则可以使用集合组查询来查询所有MySubcollection子集合,并检测父文档是否存在。下面用JavaScript编写的代码就可以做到这一点。

const db = firebase.firestore();
const parentDocReferences = [];
const deletedParentDocIds = [];
db.collectionGroup('MySubcollection')
.get()
.then((querySnapshot) => {
querySnapshot.forEach((doc) => {
console.log(doc.id);
console.log(doc.ref.parent.parent.path);
parentDocReferences.push(db.doc(doc.ref.parent.parent.path).get());
});
return Promise.all(parentDocReferences);
})
.then((docSnapshots) => {
docSnapshots.forEach((doc) => {
console.log(doc.id);
console.log(doc.exists);
if (!doc.exists && deletedParentDocIds.indexOf(doc.id) === -1) {
deletedParentDocIds.push(doc.id);
}
});

// Use the deletedParentDocIds array
// For example, get all orphan subcollections reference in order to delete all the documents in those collections (see https://firebase.google.com/docs/firestore/manage-data/delete-data#collections)
deletedParentDocIds.forEach(docId => {

const orphanSubCollectionRef = db.collection(`MyCollection/${docId}/MySubcollection`);
// ...

});

});

最新更新