Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase Transactions of Add, Delete on Multiple Nodes

I have Firebase structure which contains Users and Groups in Android. It's a many to many relationship.

Firebase Structure

When I am adding any user in the group node, I also add the group in the user node but without using any kind of transaction mechanism.

Now I need to do the delete group case where it will remove the Group node as well as the group property inside User Node where each User Joined. There must be a transaction in this scenario. So far i have dealt with the transaction code which relies on the same node but not on different node.

I need to know how to implement transaction in case of adding and deletion on multiple nodes or is there a better way of implementing it.

like image 768
topgun263 Avatar asked Jan 18 '26 10:01

topgun263


1 Answers

Firebase Database transactions work on a single node. So if you want to use a transaction, you'll have to move that up to work on the entire database. That will most certainly kill any scalability of your app, so is not a good idea.

Instead use a multi-location update to remove the affected node with one call to the database:

Map updates = new HashMap();
updates.put("/users/-Kr....", null);
updates.put("/groups/-Kr.../users/-Kr...", null);
ref.updateChildren(updates);

Now this entire operation will either succeed or fail, without requiring a transaction.

like image 59
Frank van Puffelen Avatar answered Jan 21 '26 01:01

Frank van Puffelen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!