Reputation: 1
I'm totally new to Firestore and have got really stuck my problem is, i'm using Visual studio and JavaScript to deal with my Firestore cloud functions.
I have two collections one collection holds the most recent messages that I have sent or received, the second collection contains all the documents that you have sent and received from a particular user.
I'm trying to use a cloud function trigger that when on your device you delete the most recent message, a cloud function is called that will delete the entire collection that message refers to.
I've been able to use the onDelete function, so when the most recent message is deleted the function is called and I can get all the details of the document that was deleted,
then I am able to get the path to my collection i want deleted, my problem is I have no idea how to get all the documents delete from this point. I'm pretty sure I have to do batch deletes or something like this but this is very new to me and I have searched on here and I am still quite confused any help will be appreciated.
const functions = require("firebase-functions");
const admin = require('firebase-admin');
admin.initializeApp()
exports.onDeletfunctioncalled =
// recentMsg/currentuid/touid/{documentId}' This is the path to the document that is deleted
functions.firestore.document('recentMsg/currentuid/touid/{documentId}').onDelete(async(snap, context) => {
const documentIdToCollection = context.documentId
// this is the path to the collection I want deleted
return await
admin.firestore().collection(`messages/currentuid/${documentIdToCollection}`).get()
//what do i do from here ???
});
Upvotes: 0
Views: 599
Reputation: 7388
You can use this snippets from the official documentation (select language node.js):
async function deleteCollection(db, collectionPath, batchSize) {
const collectionRef = db.collection(collectionPath);
const query = collectionRef.orderBy('__name__').limit(batchSize);
return new Promise((resolve, reject) => {
deleteQueryBatch(db, query, resolve).catch(reject);
});
}
async function deleteQueryBatch(db, query, resolve) {
const snapshot = await query.get();
const batchSize = snapshot.size;
if (batchSize === 0) {
// When there are no documents left, we are done
resolve();
return;
}
// Delete documents in a batch
const batch = db.batch();
snapshot.docs.forEach((doc) => {
batch.delete(doc.ref);
});
await batch.commit();
// Recurse on the next process tick, to avoid
// exploding the stack.
process.nextTick(() => {
deleteQueryBatch(db, query, resolve);
});
}
I would also add this to you cloud function:
if (context.authType === 'ADMIN') {
return null
}
It will avoid that the function run again when you delete the docs from the collection. Othervise each deletion will trogger the function and it will unnecessery for each deleted document.
Upvotes: 1