Reputation: 488
I am aware that you can do batched, atomic all or nothing updates using update - but can you do the same thing with a transaction?
Currently I am trying to increment a users friend count (2 users) at the same time when the friend request is accepted.
Here is what I am doing which works, but if something goes wrong it will lead to bad data inconsistencies which came about a couple times.
const upOneFriend = firebase
.database()
.ref("users")
.child(friend.uid)
.child("friendCount");
const upOneCurrentUser = firebase
.database()
.ref("users")
.child(userUid)
.child("friendCount");
upOneFriend
.transaction(currentCount => {
return currentCount + 1;
})
.then(() => {
upOneCurrentUser.transaction(currentCount2 => {
return currentCount2 + 1;
});
})
.catch(() => {
console.log("error increment");
});
Like I said, is works, but I need to do this at the same time! I have looked around and have not found anything related to batch transactions for the Realtime Database.
Cheers.
Upvotes: 0
Views: 500
Reputation: 598718
Transactions in Firebase Realtime Database work on a single node. If you need to update multiple nodes in a transaction, you'll need to run the transaction on the first common node above the ones you're looking to update. In your scenario that'd mean you run the transaction across users
, which would probably significantly reduce throughput.
An alternative would be to use a multi-location update. But since a multi-location update doesn't auto-protect against concurrent writes, you'd have to include the information to protect against that in the write itself.
For an example of this, see my answer here: Is the way the Firebase database quickstart handles counts secure?, and How to update multiple children under child node using a transaction?
Upvotes: 3