Reputation: 49
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:
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
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
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