I have the following function:
exports.tagCountDecrement = functions.database
.ref('/categoryTags/{tagName}/{postId}')
.onDelete((snapshot, context) => {
const tagsWithCountRef = admin
.database()
.ref('tags')
.child(context.params.tagName);
return tagsWithCountRef
.transaction(counter_value => {
return (counter_value || 0) - 1;
})
})
To make sure users aren't loading the node by its key (with a value of 0), I want to remove it completely if the count reaches 0. I thought about replacing the 0 with null but it needs a number to begin with if the node doesnt exist.
What is the cleanest was to go about this via firebase cloud functions?
Cheers.
You didn't supply your data, so I'm going to assume it looks something like this:
In that case, to remove the node instead of letting the count hit zero, you need to return null from the transaction whenever the value is 1 (or less, or nonexistent, since I can't think of anything reasonable to do in those cases except maybe log an error of some sort):