Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

161
Vistas
Increment/ Decrement a value in firebase realtime database with in NodeJS

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

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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

about 4 years ago · Juan Pablo Isaza Denunciar

0

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";
  //                   👇
  database.ref(path).once("value", snapshot => {
    database.ref(path).set(snapshot.val() - 1);
    console.log(snapshot.val())
  });
}
rw();

But incrementing the existing value can nowadays be done even easier (and more securely) by using the atomic server-side increment operation:

const rw = () => {
  const path = "Counter";
  //                  👇                                  👇
  database.ref(path).set(firebase.database.ServerValue.increment(1));
}
rw();
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda