Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

167
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda