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

520
Visualizações
How to write data in Firebase Realtime Database as [custom key : value] in React?

What I'm trying to achieve is having random IDs in a dedicated node in Firebase Realtime Database, while being able to check if an ID already exists in the node before writing it to prevent duplicity.
I'm working with web React (JavaScript).

The database currently looks like this:

Current database nodes

What I'm aiming for is to have another node with IDs in the following format:

Database with desired data format

Note: Generated IDs in 'users' node are different from those in 'ids', they're not connected.

ID keys in [key : value] pairs, such as 'abcd', shouldn't be generated by Firebase (as push() method does).
Instead, IDs are generated separately before writing data.

So far, I've found a few resources with similar questions, but they were either related to a different platform with another syntax or outdated.

My current code to read IDs from the 'ids' node appears to be working, if the node with IDs is manually created in database console, but it appears that I still need help with the code to write data in the desired format.

This is the code for reading data:

function checkIdDuplicity(id)
{
    const database = getDatabase();

    get(child(ref(database), 'ids/'))
     .then((snapshot) => {
        if (snapshot.exists()) {
            // Snapshot exists, find possible duplicate
            if (snapshot.hasChild(id)) {
                // Such ID is already in database
                console.log("ID already exists");
                return true;
            }
            else {
                // ID is unique
                return false;
            }
        }
        else {
            // No IDs in database, node shall be created
            return false;
        }
     })
     .catch((error) => {
        console.log(error);
     });
}

Would anyone have any ideas? 🙂

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

To add a node with custom key, you need to use set() instead of push().

const nodeRef = child(ref(database), "ids/" + id); // id = custom ID you want to specify 

await set(nodeRef, { ...data })

Also, you are downloading entire ids/ node to check existence of a given ID. Instead you can just download that particular ID:

// specify the custom ID to check for in ref
get(child(ref(database), 'ids/' + id)) .then((snapshot) => {
  if (snapshot.exists()) {
    console.log("ID already exists in database")
  } else {
    console.log("ID does not exist in database")
  }
})
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