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

265
Visualizações
Firebase: how to add auto-generated document id to the document in svelte?

What is the right way to add a firebase document with an auto-generated id in svelte?

So far I am using the following code snippet:

db.collection('colname').add({ id:'temp', text:'sometext' }).then(
    result=>{
        db.collection('colname').doc(result.id).update({id: result.id});
    }
);

What I don't like about this solution:

  1. There are 2 separate interactions with database;
  2. Svelte renders the content 2 times, i.e. after each database interaction. This is also the reason why I need to add a temporary id in add().

Is there any neater solution?


Context:

I want to pass the document as a parameter to a svelte SvelteSubComponent:

let docs = [];
db.collection('colname').onSnapshot(data =>{
    docs=data.docs;    
});

(...)

{#each docs as doc}
<SvelteSubComponent {...doc.data()}/>
{/each}

I want to be able to access the document id in the SvelteSubComponent.

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

0

If you simply need a unique, random ID I'd recommend using the UUID library (npm install uuid) and specifically UUID v4.

Then you would use it as follows:

import { v4 as uuidv4 } from 'uuid';
...
db.collection('colname').add({ id: uuidv4(), text:'sometext' }).then(...);

The generated ID will be a unique randomly generated string of the form '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed'.

about 4 years ago · Juan Pablo Isaza Relatório

0

The add() method will generate a random document ID every time. If you want to add the document ID in the document data as well then it'll be best to generate the ID beforehand and then using set() to create a document with that ID:

const docId = db.collection('colname').doc().id

db.collection('colname').doc(docId).set({ id: docId, text:'sometext' }).then(() => {
  console.log("Document added")
})
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