繁体   English   中英

如何为点击的文档获取自动生成的 id

[英]How to obtain auto-generated id for clicked documents

我使用Vue和Firestore。

我通过下面的代码在集合中生成了文档。

<template>
  <input type="text" v-model="form.title">
</template>

methods: {
  async saveform () {
    await db.collection('forms').add(
      {
        title: this.title
      }
    )
  }
}

我通过下面的代码阅读了它。

<div v-for="(form, i) in forms" :key="form.id">
  {{form.title}}
<button @click="readid">readid</button>
<button @click="deleteform">delete</button>
</div>

async created () {
  const sn = await db.collection('forms').get()
  sn.forEach(doc => {
    const { title } = doc.data()
    this.forms.push({
      title
    })
  })

火库 img

我想通过单击上面代码中的 readit 按钮来获取单击的表单的 ID。

因为要使用 db.collection('forms').doc().delete()

这是因为我需要知道点击表单的 ID 才能将 id 放入 doc() 中。

请帮我。 Firestore官方文档不足以处理自动生成的id。

如果没有足够的解释,请发表评论。 我愿意编辑。 在弄清楚这一点之前我不会睡觉,所以我可以随时编辑它。

-edited-对不起,我没有正确解释它。 我不只是知道身份证。 当我单击表单中的删除按钮时,我想创建一个删除表单的代码。

我想我会改变问题并再次发布。

要获取已创建文档的id ,您可以使用以下代码:

const formSnap=await db.collection('forms').add(
      {
        title: this.title
      }
    )

//your id
console.log('id',formSnap.id)

如果您想在添加任何数据之前获取id ,您可以这样做:

const ref = db.collection("forms").doc();
console.log('id',ref .id)

如果您在循环中需要它:

async created () {
  const sn = await db.collection('forms').get()
  sn.forEach(doc => {
    const { title } = doc.data()
    console.log('id',doc.id) // here is it in the loop
    this.forms.push({
      title
    })
  })

要通过单击按钮删除表单数据,您首先需要将formID值存储在某处,然后使用它来删除表单数据:



methods: {
  async saveform () {
    const formSnap=await db.collection('forms').add(
      {
        title: this.title
      }
    )

  return formSnap.id
  },
async deleteform(fID) {
   await db.collection('forms').doc(fID).delete()
  }
}

并这样称呼它:

await deleteform(formID)

在我的应用程序中,我可以使用以下代码:

let response = await firestore.collection("db").doc(dbId).get();
this.file = response.data();
console.log("doc id", response.id);

所以我认为这应该有效:

const sn = await db.collection('forms').get();

sn.forEach(doc => {
    const { title } = doc.data()
    const id = doc.id // <-- This is it
    
    this.forms.push({
        title
    });
})

好的,如果您想在调用“deleteform” function 时删除文档,那么这应该可以:

// Your Template
<div v-for="(form, i) in forms" :key="form.id">
    {{form.title}}
    <button @click="readid">readid</button>
    <button @click="deleteform(form.id)">delete</button>
</div>

// Your created hook
async created () {
    const sn = await db.collection('forms').get();

    sn.forEach(doc => {
        const { title } = doc.data()
        const id = doc.id // <-- This is it
    
        this.forms.push({
            title,
            id,
        });
    })
}

// And your function for deleting the document
async deleteform(docId) {
    await db.collection('forms').doc(docId).delete()
}

希望我能帮助你!

暂无
暂无

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

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