I'm using Firebase as the backend to my Flutter project. I need to write to multiple nodes in one transaction. Now I have:
await (_firebaseDatabase
.reference()
.child('user_data').Push().set({"userName":"aaa"}));
await (_firebaseDatabase
.reference()
.child('user_history').Push().set({"userName":"aaa"}));
But these are 2 transactions
, so 1 could end successfully but another one could fail and I want to prevent from happening this.
Another case is to write to user_data
and update to user_history
. How can we achieve this in a firebase real-time database?
Basically, I want to do insert and update at 2 different nodes in a single transaction so that data doesn't get mismatched.
CodePudding user response:
What you are looking for is known as a multi-path write operation, which allows you to write to multiple, non-overlapping paths with a single update
call. You can specify the entire path to update for each key, and the database will then set the value you specify at that specific path.
To generate two separate unique keys, you can call push()
twice without any arguments. When called like that, it doesn't actually write to the database, but merely generates a unique reference client-side, that you can then get the key from.
Combined, it would look something like this:
const db = _firebaseDatabase.reference();
const key1 = db.push().key;
const key2 = db.push().key;
const values = {};
values["user_data/" key1 "/username"] = "aaa";
values["user_history/" key2 "/username"] = "aaa";
db.update(values);