Reputation: 3793
I'm playing around with Firebase Cloud Functions and Cloud Firestore (NodeJS + TypeScript on top).
I created two collections: apps
and devices
. I also have 2 functions: one of my functions is deleting an app from the apps
collection (requested over HTTPS), and the other function is reacting to that app being deleted. Second function's job is deleting all devices associated with the deleted app (each device has an 'appId' property).
I won't post the HTTPS one, as I can verify that it works ok. I will post only the Firestore data deleted reaction:
export const onAppDeleted = functions.firestore
.document("apps/{appId}")
.onDelete((document, context) => {
const appId = context.params.appId;
return admin.firestore().collection(COL_DEVICES).where('appId', '==', appId).get()
.then((results) => {
const batch = admin.firestore().batch();
results.forEach((record) => {
batch.delete(record.ref)
});
return batch.commit();
});
});
PROBLEM: This approach deletes the whole devices
collection
EXPECTED: Delete only the devices that match the deleted app, not the whole collection
Notes:
(1) this might be happening because I only have this one device in the devices
collection, but still... I want to keep the collection (do I?)
(2) I have close to zero experience with Firestore & Cloud Functions, so please correct me if my approach is wrong
Upvotes: 0
Views: 84
Reputation: 317477
Collections don't really "exist" in the way that you're thinking. If you write a document into a collection that you don't see in the console, it will suddenly appear if you refresh the console - it doesn't need to be created explicitly. Similarly, if you delete the last document in a collection and refresh the console, the collection will disappear. You can see from this behavior that they aren't like filesystem directories that can exist with no files in them.
So, there's nothing you have to do differently, just expect the collection to disappear after all of its documents are gone.
Upvotes: 1