简体   繁体   English

Firebase:如何将自动生成的文档 ID 添加到 svelte 中的文档?

[英]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?在 svelte 中添加具有自动生成的 id 的 firebase 文档的正确方法是什么?

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 个单独的交互;
  2. Svelte renders the content 2 times, ie after each database interaction. Svelte 将内容呈现 2 次,即在每次数据库交互之后。 This is also the reason why I need to add a temporary id in add().这也是我需要在add()中添加一个临时id的原因。

Is there any neater solution?有没有更简洁的解决方案?


Context :上下文

I want to pass the document as a parameter to a svelte SvelteSubComponent:我想将文档作为参数传递给一个苗条的 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.我希望能够访问 SvelteSubComponent 中的文档 ID。

If you simply need a unique, random ID I'd recommend using the UUID library ( npm install uuid ) and specifically UUID v4 .如果您只需要一个唯一的随机 ID,我建议您使用UUID 库npm install uuid ),特别是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' .生成的 ID 将是一个唯一的随机生成的字符串,形式为'1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed'

The add() method will generate a random document ID every time. add()方法每次都会生成一个随机的文档 ID。 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:如果您还想在文档数据中添加文档 ID,那么最好事先生成 ID,然后使用set()创建具有该 ID 的文档:

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

db.collection('colname').doc(docId).set({ id: docId, text:'sometext' }).then(() => {
  console.log("Document added")
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM