I have an issue with firebase database functions. The documentation contains the following minimal example to work with transactional data:
var upvotesRef = db.ref("server/saving-data/fireblog/posts/-JRHTHaIs-jNPLXOQivY/upvotes");
upvotesRef.transaction(function (current_value) {
return (current_value || 0) + 1;
});
Now, my firebase database structure looks like the following
/game-results
/RaUALJvTZVea5y6h1lzqGJPMpuI3
/distance
/score
/timestamp
/3ItAqKHL0XRUOum2Ajdz9hHQxMs1
/distance
/score
/timestamp
/statistics
/total-distance
/total-score
And I would like to sum up the scores and distances to a total. I'm using the following function, here for total-distance
:
const functions = require('firebase-functions');
exports.updateTotalDistance = functions.database.ref('/game-results/{userId}/distance')
.onWrite(event => {
const newDistance = event.data.val();
const distanceRef = functions.database.ref('/statistics/total-distance')
return distanceRef.transaction(function(currentDistance) {
console.log('currentDistance', currentDistance);
return (currentDistance || 0) + newDistance;
});
});
However, I can not wrap my head around why I get the following error in the firebase function logs:
TypeError: distanceRef.transaction is not a function
at exports.updateTotalDistance.functions.database.ref.onWrite.event (/user_code/index.js:19:22)
at /user_code/node_modules/firebase-functions/lib/cloud-functions.js:35:20
at process._tickDomainCallback (internal/process/next_tick.js:129:7)
Why is the Database reference not allowing me to write transactional data? All I want to do is to sum up all scores and distances.
functions.database.ref
is not what you are looking for, that's the builder for listeners. You'll want to use event.data.ref
or admin.database().ref
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With