emixd
emixd

Reputation: 49

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.

Upvotes: 1

Views: 634

Answers (2)

Dharmaraj
Dharmaraj

Reputation: 50930

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")
})

Upvotes: 0

Thomas Hennes
Thomas Hennes

Reputation: 9979

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

Upvotes: 1

Related Questions