Reputation: 3384
My database structure is:
- Scores
- r5rwuerpepdsoazdf (user UID)
- scoreString: "5,12"
- j6fdasdfsdfs08fdd
- scoreString: "1,4,7"
and I have a cloud function that updates the Score for a particular user UID when a value is written in another node (ScoreStacks):
exports.updateScoreString =
functions.database.ref('/ScoreStacks/{uid}/{levelKey}/Score')
.onWrite((dataSnapshot, context) => {
const score = dataSnapshot.after.val();
const scoreStringRef = dataSnapshot.after.ref.root.child('Scores/' + context.params.uid + '/scoreString');
return scoreStringRef.transaction(scoreString => {
if (!scoreString) // transactions return null first time
{
return scoreString;
}
return scoreStringWithAddedScore(scoreString, score);
});
});
This is all working fine apart from if the UID in the Scores node does not yet exist. Then nothing happens. I guess that is fair enough because scoreStringRef is refering to a path that doesn't exist.
So how can I ensure a new entry is made in the Scores node if the UID does not exist yet? It all has to be done atomically.
Upvotes: 0
Views: 98
Reputation: 598728
It's hard to be sure without seeing scoreStringWithAddedScore
, but I suspect you want this:
return scoreStringRef.transaction(scoreString => {
if (!scoreString) // transactions return null first time
{
scoreString = "";
}
return scoreStringWithAddedScore(scoreString, score);
});
A more concise (but somewhat harder to parse if you're new to this) version:
return scoreStringRef.transaction(scoreString => {
return scoreStringWithAddedScore(scoreString || "", score);
});
Upvotes: 1