I have an filmOrders
collection and when a document is created there, it creates documents in 7 other collections. I wanted to delete a document from filmOrders
and delete all documents from the other collections that have that ID from filmOrders
.
To make this happen, the ID of the document in filmOrders
is stored in those documents and then I can just query the ID in the other 7 collections and delete them via a transaction.
The issue is, I'm not sure if I'm doing this correctly. I've read this question which says you can't use a query reference in a transaction. But below I'm querying the db, getting the docs and then using a transaction to delete the docs.
Is this the right way to do this? It's possible for more documents to get added with an ID from filmOrders
so I'm not sure if those will get deleted while this transaction is running
"use strict";
const functions = require("firebase-functions");
const admin = require("firebase-admin");
exports.deleteOrderAndInformation = functions.https.onCall(
async (data, context) => {
const { admin: adminToken, pa } = context.auth.token;
if (!adminToken && !pa)
throw new functions.https.HttpsError(
"permission-denied",
"Insufficent permissions to delete order"
);
try {
const db = admin.firestore();
await db.runTransaction(async t => {
//we have to identify the docs to use in the transaction ahead of time
//https://stackoverflow.com/questions/50071700/can-we-not-query-collections-inside-transactions
const { orderId } = data;
const orderRef = db.doc(`filmOrders/${orderId}`);
//get all batches and events that had that orderID in it
const batchCols = [
"extrusionBatches",
"printingBatches",
"laminationBatches",
"slittingBatches",
"conversionBatches",
"filmBatches",
"filmEvents"
];
const queriesPromises = batchCols.map(col => {
return db
.collection(col)
.where("orderId", "==", orderId)
.get();
});
//this will return all the query snapshots
const queriesResolved = await Promise.all(queriesPromises);
//extract the document refs
const docRefs = queriesResolved.map(qSnapshot => {
return qSnapshot.docs.map(doc => doc.ref);
});
const docRefsFlat = docRefs.flat();
const tDocs = await t.getAll(...docRefsFlat, orderRef);
const tDelete = tDocs.map(doc => {
return t.delete(doc.ref);
});
await Promise.all(tDelete);
});
} catch (error) {
throw new functions.https.HttpsError("cancelled", error.toString());
}
}
);