Home > Mobile >  Increment/ Decrement a value in firebase realtime database with in NodeJS
Increment/ Decrement a value in firebase realtime database with in NodeJS

Time:11-23

I want to setup a counter in my firebase realtime database. In my app trying to use it for counting number of API requests. Below is the shortest and simplest extraction of the code from my app which works exactly same and produce same error as in my app.

Structure of my firebase realtime database:

Counter: 1000

My code(indd.js):

require('dotenv').config();

const admin = require("firebase-admin");
admin.initializeApp({
  credential: admin.credential.applicationDefault(),
  databaseURL: "https://awesomeURL.firebaseio.com"
});

const database = admin.database();

const rw = () => {
  const path = "Counter";
  database.ref(path).on("value", snapshot => {
    database.ref(path).set(snapshot.val() - 1);
    console.log(snapshot.val())
  });
}


rw();

Content of my package.json file

  "name": "api",
  "version": "1.0.0",
  "description": "All my APIs.",
  "main": "indd.js",
  "dependencies": {
    "dotenv": "^10.0.0",
    "firebase-admin": "^8.6.1"
  },
  "scripts": {
    "start": "nodemon indd.js"
  },
  "engines": {
    "node": ">=12"
  }
}

The content of my .env file.

The required json file is available in Project Overview ⚙️ > Service accounts > Generate new private key

GOOGLE_APPLICATION_CREDENTIALS = ./adminsdk.json

Result:

Data is successfully decremented in the firebase realtime database and the application crashes producing following error. Pastebin Link Of Error Message On Console

CodePudding user response:

database.ref(path).on("value", snapshot => {
    database.ref(path).set(snapshot.val() - 1);
    console.log(snapshot.val())
  });

So here on method fire as soon as you update the value, which again update the value, So this is creating a loop

update value -> on method fired -> update value -> on method fired ->..... infinite.

Instead of using on method, read value once using get or similar method then update your value

Note :- A better way would be using transaction

CodePudding user response:

You're attaching a permanent listener to the Counter by calling on. So you code will be called once with the initial value of the counter, and then every time the counter is changed.

And since your callback code changed the counter, that will cause the callback to be called again... and again... and again, until you get the error you got.

To increment the value, you should only get the current value, and not listen for updates, which you can do by using once() instead of on():

const rw = () => {
  const path = "Counter";
  //                              
  • Related