Reputation: 87
I have a Firestore collection called Posts, and each document in Posts could have a sub-collection called Post-Likes and/or Post-Comments. When I delete the Posts document, it does not delete the sub-collection so I am left with a reference to a missing document in Firestore which looks like this:
I am using the following code in my Google Cloud Function to find references in the Post collection with missing data, then for each document with a missing reference, I want to delete the sub-collections Post-Likes and Post-Comments. For now, I am just try to list the sub-collection document so I can delete them, but I am getting an error.
function deleteOrphanPostSubCollections() {
let collectionRef = db.collection('Posts');
return collectionRef.listDocuments().then(documentRefs => {
return db.getAll(...documentRefs);
}).then(documentSnapshots => {
for (let documentSnapshot of documentSnapshots) {
if (documentSnapshot.exists) {
console.log(`Found document with data: ${documentSnapshot.id}`);
} else {
console.log(`Found missing document: ${documentSnapshot.id}`);
return documentSnapshot.getCollections().then(collections => {
return collections.forEach(collection => {
console.log('Found subcollection with id:', collection.id);
});
});
}
}
return
});
}
However, I am getting the following error. Please help me resolve this issue.
Upvotes: 0
Views: 147
Reputation: 83163
This is because there is not getCollections()
method for a DocumentSnapshot
.
If you want to list all the collections of the Document corresponding to the DocumentSnapshot
, you need to use the listCollections()
method, as follows:
documentSnapshot.ref.listCollections()
.then(collections => {
for (let collection of collections) {
console.log(`Found subcollection with id: ${collection.id}`);
}
});
In addition, note that if you call an asynchronous method in a loop, it is recommended to use Promise.all()
in order to return a single Promise that resolves when all the "input" Promises are resolved.
Upvotes: 2