简体   繁体   中英

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?

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 .

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM