I want to clean my collection data. I have the collection name "teams". It has data and sub-collection name "players".
I have deleted "teams" document by simple delete query of Firestore but as we know we can't delete sub-collection (players) by deleting main/ancestor docID. We must have to fetch all the documents from "players" collection and then delete them first. After we should delete the ancestor (teams' doc) document so it will be clear all for the collection.
It's not possible to fetch those orphaned documents from "teams" collection. so what is the way to clean these documents from the collection?
~ PS: I have created a firebase cloud function to delete sub-collections documents while deleting the ancestor doc.
exports.deleteOrphanedTeamsDoc = functions.firestore
.document('teams/{teamID}')
.onDelete(async (snap, context) => {
var teamID = context.params.teamID;
console.log("Deleted teamID --->>> " + teamID);
const store = admin.firestore();
var teamsPlayer = await store.collection('teams').doc(teamID).collection('players').get()
teamsPlayer.docs.forEach(async(val) => {
await store.collection('teams').doc(teamID).collection('players').doc(val.id).delete();
});
});
So with the help of the above code, I can delete fresh teams docID with sub-collections too.
But what about all the orphaned docs that available in my "teams" collection.
Update 1:
I tried the code of Renaud Tarnec, Sorry but I am new to function so not many ideas for it. I clicked on the run button but getting some issues
6:46:13.625 pm
scheduledFunction
Function execution took 12608 ms, finished with status: 'error'
6:46:13.622 pm
scheduledFunction
at processTicksAndRejections (internal/process/task_queues.js:97:5)
6:46:13.622 pm
scheduledFunction
at runMicrotasks (<anonymous>)
6:46:13.622 pm
scheduledFunction
at /workspace/index.js:161:53
6:46:13.622 pm
scheduledFunction
ReferenceError: promises is not defined
6:46:01.018 pm
scheduledFunction
Function execution started
I think issues is here ReferenceError: promises is not defined
at
const parentsSnapshotsArray = await Promise.all(promises);