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

269
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 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