Willy
Willy

Reputation: 332

How to access snapshot of Firebase database within Firebase Function?

Every hour, I want my firebase function to look through my database, read a value, calculate a new value from this old value, and then update it in the database. I am having trouble accessing a snapshot of the data. Specificically,

exports.scheduledFunction = functions.pubsub.schedule('every 1 hour').onRun((context) => {
  const ref = functions.database.ref('/users/test_user/commutes');
  ref.once('value',function(snapshot) {
   // do new calculation here

  }, function (errorObject) {
    console.log("The read failed: " + errorObject.code);
  });
  return null;
});

I am getting a : functions: TypeError: ref.once is not a function error.

How do I access a value from my firebase real time database and update it from a Firebase function?

Upvotes: 0

Views: 247

Answers (2)

Peter Haddad
Peter Haddad

Reputation: 80944

The firebase-functions is different from the client side. The ref() function according to the docs:

ref: function

ref(path: string): RefBuilder

Select Firebase Realtime Database Reference to listen to.

Path of the database to listen to.

Returns RefBuilder

The RefBuilder will contain the database triggers that you can call, onCreate(), onWrite(). To be able to use your database, then you need to use the admin sdk.

https://firebase.google.com/docs/reference/functions/providers_database_.refbuilder

Upvotes: 0

Doug Stevenson
Doug Stevenson

Reputation: 317808

You're trying to use the firebase-functions SDK to query the database. It can't do that. You will have to use the Firebase Admin SDK to make the query.

You will need to get started like this (not complete, but you should be able to see what you need to do). Import and initialize at the global scope:

const admin = require('firebase-admin')
admin.initializeApp()

Then in your function, use it. Be sure to work with promises correctly.

const ref = admin.database().ref('...')
return ref.once('value').then(snapshot => {
    // work with the snapshot here, and return another promise
    // that resolves after all your updates are complete
})

Upvotes: 1

Related Questions