Tom Darious
Tom Darious

Reputation: 533

Can't change data in Firebase Realtime Database when using Cloud Functions

I want to reset a specific value in my Firebase Realtime Database every day at 12:00 AM. I'm using Firebase Cloud Functions to do this. This is the code that I have:

exports.dailyReset = functions.pubsub.schedule('0 0 * * *').onRun((context) => {
  exports.resetValue = functions.database.ref('/users/{userId}')
      .onWrite((change, context) => {
        var ref = change.data.ref;
        ref.update({
            "daily": 0
        });
        return ref.update({"daily": 0});
      });
  return null;
});

Upon testing the script, it doesn't work. It's not resetting the value in my Firebase Realtime Database. Can someone tell me how do I fix this?

Upvotes: 0

Views: 513

Answers (3)

Android Developer
Android Developer

Reputation: 1

const { onSchedule } = require("firebase-functions/v2/scheduler");
const { logger } = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();

exports.updatePoints = onSchedule("every day 17:30", async (event) => {
  await admin.database().ref("USERDATA/").once("value")
    .then(function(snapshot) {
      const users = snapshot.val();
      logger.log(users);
    });
}

Use await, so its working for me I'm using visual studio code, windows 11, nodejs

Upvotes: 0

Frank van Puffelen
Frank van Puffelen

Reputation: 600110

The Cloud Functions triggers in your index.js file have to be known and fixed when run firebase deploy. That means you can't dynamically create triggers from inside a Cloud Functions, as you're trying to do.

The common approaches for dynamic scheduling are:

  1. Have a single Cloud Function that runs periodically and then executes the tasks for the past time period.
  2. Dynamically schedule Cloud Functions with Cloud Tasks, as Doug describes in his blog post How to schedule a Cloud Function to run in the future with Cloud Tasks (to build a Firestore document TTL).

But in your case, why do you even need the onWrite trigger? Can't you just import the Admin SDK, user that to read all users, and then delete them?

Upvotes: 1

Doug Stevenson
Doug Stevenson

Reputation: 317928

It's not possible to use the Functions SDK to write to the database. functions can only be used to establish triggers that run when the triggering event occurs.

In other words, functions.database.ref('/users/{userId}').onWrite() isn't going to write anything at all.

If you want to write to Realtime Database from a nodejs program, you should use the Firebase Admin SDK to write data.

Upvotes: 1

Related Questions