Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find orphaned subcollection documents

The firestore docs say:

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.

Is there any way to access these documents if you lose the reference do db.collection('coll').doc('doc')? Say for example client A goes offline, and then creates coll/doc/subcoll/foo. Then the server deletes coll/doc and it's subcollections. Later client A comes back online and syncs foo. It appears that now there's now way for me to know that foo exists and is wasting space in the database.

like image 832
ribrdb Avatar asked May 02 '26 22:05

ribrdb


1 Answers

It should be possible to retrieve all documents of the sub-collection (including orphans) with .collectionGroup('subcoll').

Then you can iterate over them with .forEach() and retrieve their parent with .getParent().

If they don't have a parent, they are an orphan and you can delete them.

like image 57
adius Avatar answered May 07 '26 10:05

adius



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!