I am using transaction in my realtime database as follows:
admin.database().ref(`/users/${uid}`).transaction((user) => {
if (user) {
console.log("user exists");
// ... modify the user ...
admin.database().ref(`/notifications/${user.guid}`).transaction((notification) => {
// modify notification object
}
return user;
} else {
console.log("user did not exist");
return { /* information about a new user */ };
}
});
The results have been strange. I am seeing two console.logs as follows:
> user did not exist
> user exists
Even though the user object existed. What ends up happening is that I have a user that gets created, overwriting the old user.
I've tried removing the nested notification transaction within the transaction, and it seems to work then, but I still get the same first > user did not exist
console.log()
output, and it's not clear why that would be.
I guess there are two questions here. First is why the non-existing code path executes at all, and the second is how, if not like this, should I pass along a value that I retrieved from read part of the transaction to another write.
Thanks!
As explained in the doc, the Transaction function is called multiple Times
Your transaction handler is called multiple times and must be able to handle null data. Even if there is existing data in your database it may not be locally cached when the transaction function is run.
This is why the console first write that there is no user and then write that there is a user.
Note that you should not call a Transaction within a Transaction.