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

Tom Darious

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?

Frank van Puffelen

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.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

How to push new data into firebase realtime database using cloud functions?

From Dev

how to update a value in firebase realtime database using Cloud Functions for Firebase

From Dev

How to fetch data from firebase-realtime-database using firebase cloud functions?

From Dev

How to use scheduler for Firebase Cloud Functions with Realtime Database/Analytics triggers?

From Dev

How to create new Firebase Realtime Database Instance using Cloud Functions?

From Dev

How can I change the left parameter as String while writing in my Firebase Realtime Database in Functions?

From Dev

how to read data from firebase with admin sdk in cloud functions with typescript

From Dev

In Firebase Realtime Database, how can an unauthenticated third-party server (using the Admin SDK) read unprotected data from my database?

From Dev

Dynamically assign a key value when writing a new data to firebase realtime database using firebase cloud functions

From Dev

How do I get data from a firebase realtime database and change one text field to represent that specific record?

From Dev

How do I get data from firebase realtime database in web?

From Dev

How do I fetch data from Firebase Realtime database?

From Dev

How do I export data from Firebase Realtime Database?

From Dev

How do I read and return data from firebase realtime database?

From Dev

How do I find a specific path on the firebase realtime database then change the value at that path using a Text Input?

From Android

how do i retrieve data from firebase realtime database using kotlin

From Dev

How do I fetch data from firebase realtime database which are children to a random key - using react native?

From Dev

Firebase Realtime Database and Cloud Functions -- increment counter based on data nodes

From Dev

How to Write Data Into Firebase Realtime Database with Cloud Functions when new Data is added to a Specific Child

From Dev

How to add a new field in Array of data in Firebase realtime database using Firebase Functions?

From Dev

How to listen to realtime database changes (like a stream) in firebase cloud functions?

From Dev

How to access multiple Realtime Database instances in Cloud Functions for Firebase

From Dev

How to trigger realtime database field in Google Cloud server (not in functions of Firebase)

From Dev

Firebase Realtime Database - how to manage database rules using java sdk

From Dev

How can I push a JSON to firebase realtime database from cloud functions?

From Android

How to create a new parent node outside the .ref(/path) in Firebase Realtime Database using Cloud Functions (Typescript)?

From Java

Get information from Firebase Realtime Database with Firebase Admin SDK

From Dev

Send data from Realtime Database using Firebase Functions to email

From Dev

how to do a cloud function firebase importing data from Bucket to database realtime

Related Related

  1. 1

    How to push new data into firebase realtime database using cloud functions?

  2. 2

    how to update a value in firebase realtime database using Cloud Functions for Firebase

  3. 3

    How to fetch data from firebase-realtime-database using firebase cloud functions?

  4. 4

    How to use scheduler for Firebase Cloud Functions with Realtime Database/Analytics triggers?

  5. 5

    How to create new Firebase Realtime Database Instance using Cloud Functions?

  6. 6

    How can I change the left parameter as String while writing in my Firebase Realtime Database in Functions?

  7. 7

    how to read data from firebase with admin sdk in cloud functions with typescript

  8. 8

    In Firebase Realtime Database, how can an unauthenticated third-party server (using the Admin SDK) read unprotected data from my database?

  9. 9

    Dynamically assign a key value when writing a new data to firebase realtime database using firebase cloud functions

  10. 10

    How do I get data from a firebase realtime database and change one text field to represent that specific record?

  11. 11

    How do I get data from firebase realtime database in web?

  12. 12

    How do I fetch data from Firebase Realtime database?

  13. 13

    How do I export data from Firebase Realtime Database?

  14. 14

    How do I read and return data from firebase realtime database?

  15. 15

    How do I find a specific path on the firebase realtime database then change the value at that path using a Text Input?

  16. 16

    how do i retrieve data from firebase realtime database using kotlin

  17. 17

    How do I fetch data from firebase realtime database which are children to a random key - using react native?

  18. 18

    Firebase Realtime Database and Cloud Functions -- increment counter based on data nodes

  19. 19

    How to Write Data Into Firebase Realtime Database with Cloud Functions when new Data is added to a Specific Child

  20. 20

    How to add a new field in Array of data in Firebase realtime database using Firebase Functions?

  21. 21

    How to listen to realtime database changes (like a stream) in firebase cloud functions?

  22. 22

    How to access multiple Realtime Database instances in Cloud Functions for Firebase

  23. 23

    How to trigger realtime database field in Google Cloud server (not in functions of Firebase)

  24. 24

    Firebase Realtime Database - how to manage database rules using java sdk

  25. 25

    How can I push a JSON to firebase realtime database from cloud functions?

  26. 26

    How to create a new parent node outside the .ref(/path) in Firebase Realtime Database using Cloud Functions (Typescript)?

  27. 27

    Get information from Firebase Realtime Database with Firebase Admin SDK

  28. 28

    Send data from Realtime Database using Firebase Functions to email

  29. 29

    how to do a cloud function firebase importing data from Bucket to database realtime

HotTag

Archive