简体   繁体   English

查找孤立的子集合文档

[英]Find orphaned subcollection documents

The firestore docs say: Firestore 文档说:

When you delete a document that has associated subcollections, the subcollections are not deleted.当您删除具有关联子集合的文档时,子集合不会被删除。 They are still accessible by reference.它们仍然可以通过引用访问。 For example, there may be a document referenced by db.collection('coll').doc('doc').collection('subcoll').doc('subdoc') even though the document referenced by db.collection('coll').doc('doc') no longer exists.例如,可能存在db.collection('coll').doc('doc').collection('subcoll').doc('subdoc')引用的文档,即使db.collection('coll').doc('doc')不再存在。

Is there any way to access these documents if you lose the reference do db.collection('coll').doc('doc') ?如果您丢失了引用 do db.collection('coll').doc('doc') ,有没有办法访问这些文档? Say for example client A goes offline, and then creates coll/doc/subcoll/foo .比如说客户端 A 离线,然后创建coll/doc/subcoll/foo Then the server deletes coll/doc and it's subcollections.然后服务器删除coll/doc及其子集合。 Later client A comes back online and syncs foo.稍后客户端 A 恢复在线并同步 foo。 It appears that now there's now way for me to know that foo exists and is wasting space in the database.看来现在我有办法知道 foo 存在并且正在浪费数据库中的空间。

It is possible to get the access to these documents. 可以访问这些文档。 Save IDs somewhere when users delete the documents. 用户删除文档时,将ID保存在某处。 Or just find out the document ID in console.firebase.google.com. 或者只是在console.firebase.google.com中找到文档ID。 If you have ID of removed doc you will able to fetch the subcollection's docs. 如果您具有已删除文档的ID,则可以获取子集合的文档。 The removed doc ID marked italic in Firebase Console ( like this one ). 在Firebase控制台中,已删除的文档ID标记为斜体( 例如这一点 )。

It should be possible to retrieve all documents of the sub-collection (including orphans) with .collectionGroup('subcoll') .应该可以使用.collectionGroup('subcoll')检索子集合(包括孤儿)的所有文档。

Then you can iterate over them with .forEach() and retrieve their parent with .getParent() .然后,您可以使用 .forEach() 遍历它们并使用.forEach()检索它们的父.getParent()

If they don't have a parent, they are an orphan and you can delete them.如果他们没有父母,他们就是孤儿,您可以删除他们。

Adding a cloud function to delete subcollections when a doc is deleted, can help with this problem from occurring again.在删除文档时添加云 function 以删除子集合,可以帮助避免再次出现此问题。 https://firebase.google.com/docs/firestore/solutions/delete-collections#cloud_function https://firebase.google.com/docs/firestore/solutions/delete-collections#cloud_function

exports.removeSubCollections = functions.firestore
.document("col1/{docId}")
.onWrite(async (change, context) => {
  const docId = context.params.docId;

  if(!change.after.exists) {
    //Delete all subcollections here
  }
});

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

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