TransWikia.com

How do I use Firebase Admin SDK to change data in Firebase Realtime Database while using Cloud Functions?

Stack Overflow Asked by Tom Darious on January 22, 2021

I want to reset a specific value in my Firebase Realtime Database every day at 12:00 AM. To do this, I’m using the Firebase Admin SDK to change the data in Firebase Realtime Database and Cloud Functions to trigger the change at 12:00 AM every day.

This is an example structure of my Firebase Realtime Database:

{
  "users": {
    "fa54487d9cbb4214b00db80e2118e4e6": {
      "daily": 10
    }
  }
}

This is the code in my index.js:

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

// The Firebase Admin SDK to access Cloud Firestore.
var admin = require('firebase-admin');

// Fetch the service account key JSON file contents
var serviceAccount = require("serviceAccountKey.json");

// Initialize the app with a service account, granting admin privileges
admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "https://databaseName.firebaseio.com"
});

// As an admin, the app has access to read and write all data, regardless of Security Rules
var db = admin.database();
var ref = db.ref("users");

// Reset today GHG emissions at 12:00 AM everyday
exports.dailyReset = functions.pubsub.schedule('0 0 * * *').onRun((context) => {
    usersRef.child("{userId}").set({
      daily: 0
    });
});

Deploy Error:

! functions[dailyReset(us-central1)]: Deployment error.

Function failed on loading user code. This is likely due to a bug in the user code. Error message: Error: please examine your function logs to see the error cause: https://cloud.google.com/functions/docs/monitoring/logging#viewing_logs. Additional troubleshooting documentation can be found at https://cloud.google.com/functions/docs/troubleshooting#logging. Please visit https://cloud.google.com/functions/docs/troubleshooting for in-depth troubleshooting documentation.

Firebase Console Functions Logs:

Error: function terminated. Recommended action: inspect logs for termination reason.

Additional troubleshooting documentation can be found at https://cloud.google.com/functions/docs/troubleshooting#logging Function cannot be initialized.

{"@type":"type.googleapis.com/google.cloud.audit.AuditLog","status":{"code":3,"message":"Function failed on loading user code. This is likely due to a bug in the user code.

Error message: Error: please examine your function logs to see the error cause: https://cloud.google.com/functions/docs/monitoring/logging#viewing_logs.

Additional troubleshooting documentation can be found at https://cloud.google.com/functions/docs/troubleshooting#logging.

The script won’t deploy when I use firebase deploy as my function is giving me an error. Can someone tell me how to fix my code?

One Answer

This won't work:

exports.dailyReset = functions.pubsub.schedule('0 0 * * *').onRun((context) => {
    usersRef.child("{userId}").set({
      daily: 0
    });
});

There is nothing here that interprets the {userId} in that path, so the database updates the literal path "/users/{userId}", which is not what you want.

If you know what user ID you want to update, you should use that value in the path:

exports.dailyReset = functions.pubsub.schedule('0 0 * * *').onRun((context) => {
    let usersRef = admin.database().ref("users");
    usersRef.child("theActualUserIdYouWantToUpdate").set({
      daily: 0
    });
});

If you don't know what user ID to update, you'll need to query the database to determine that.


If you want to loop over all users, you can do:

exports.dailyReset = functions.pubsub.schedule('0 0 * * *').onRun((context) => {
    return usersRef.once("value").then((snapshot) => {
        let updates = {};
        snapshot.forEach((userSnapshot) => {
            updates[userSnapshot.key+"/daily"] = 0
        });
        return usersRef.update(updates);
    });
});

If you are new to JavaScript or interacting with the Realtime Database in it, Cloud Functions for Firebase is not the best way to learn it. I recommend first reading the Firebase documentation for Web developers and/or taking the Firebase codelab for Web developer. They cover many basic JavaScript, Web and Firebase interactions. You could also use the Admin SDK in a local Node.js process, which can be debugged with a local debugger. After those you'll be much better equipped to write code for Cloud Functions too.

Correct answer by Frank van Puffelen on January 22, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP