Ad

Is There A Way To Link Subcollection In Firestore To Root Collection

I have 2 root collection which is drivers and cars. In the drivers collection, I have document that represent each of the driver. However each of driver have a sub collection which is driverCars to represent how many cars the driver registered and all the data of the car that the specific driver have.

enter image description here

I make it like this because its easy to query on how many cars are registered in the firebase and how many cars that certain driver registered. There are more query that I can use it easily for getting data from all the cars and from the cars that only specific user have. I update both collection for cars and driverCars when a driver just register the car using dart language in flutter for the backend. And if the car already exist in cars collection, then it will only updated in driverCars.However I face some problem when I want to delete the car manually in firebase. since the 2 collection not linked, I have to delete both document manually and I think it's not a good approach.

So my question is, Is there a way to prevent this. Is there a way to tell the firebase that the data of the cars in subcollection driverCars is linked to cars and if one of it was to be deleted, both will be deleted automatically.. Or is it my mistake to model the firestore collection in this way??

Ad

Answer

Is there a way to tell the firebase that the data of the cars in subcollection driverCars is linked to cars and if one of it was to be deleted, both will be deleted automatically.

Yes, one classical method is to use a Cloud Function that is triggered when one of the docs is deleted. The Cloud Function is executed in the back-end and deletes the corresponding doc in the other collection.

Have a look at the documentation. In your case you need to use the onDelete() function.

Ad
source: stackoverflow.com
Ad