Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

266
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!