Home > Mobile >  How to correct Firebase Cloud Function admin reference not a function error
How to correct Firebase Cloud Function admin reference not a function error

Time:02-15

I've recently tried to update .WriteOn cloud function into a scheduled cloud function for my firebase app. The objective is to run a function every 4 days that goes out deletes messages that are over 2 days old. This worked perfectly for the .WriteOn function but of course that meant the function was executed every time a message was created; which was overkill. Here is the function I have in my index.js file...

// The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers.
const functions = require('firebase-functions');

// The Firebase Admin SDK to access the Firebase Realtime Database.
const admin = require('firebase-admin');
admin.initializeApp()

    exports.scheduledFunction = functions.pubsub.schedule('every 96 hours').onRun(async (context) => {
      const ref = admin.database().reference('messages/{pushId}');
      var now = Date.now();
      var cutoff = now - 24 * 60 * 60 * 1000;
      var oldItemsQuery = ref.orderByChild('timeStamp').endAt(cutoff);
      return oldItemsQuery.once('value', function(snapshot) {
        // create a map with all children that need to be removed
        var updates = {};
        snapshot.forEach(function(child) {
          updates[child.key] = null
        });
        // execute all updates in one go and return the result to end the function
        return ref.update(updates);
      });
    });

Here is the execution error I'm reading on my Firebase Functions console...

scheduledFunction TypeError: admin.database(...).reference is not a function

CodePudding user response:

The error message is telling you that this line of code is calling a method that doesn't exist:

  const ref = admin.database().reference('messages/{pushId}');

In fact, there is no method called "reference" on the Database object returned by admin.database(). Using the API documentation, you can see that database() returns a Database object which further extends a different Database. In there, you'll see that there is a ref() method. There is no reference(). Maybe that's what you meant to use.

  const ref = admin.database().ref('messages/{pushId}');

Also, this is what you'll see in the example code in the documentation. Please review that to make sure you're following the correct examples for JavaScript.

  • Related