Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase TypeError: ref.transaction is not a function

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.

like image 678
Afr Avatar asked Mar 13 '17 22:03

Afr


1 Answers

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

like image 161
James Daniels Avatar answered Oct 22 '22 15:10

James Daniels