`In what way can I acquire auto-generated identifiers for selected documents?`

I am currently using Vue and Firestore in my project.

Below is the code snippet I used to generate a document in the collection:

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

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

And here is the code I used to read the documents:

<div v-for="(form, i) in forms" :key="form.id">
  {{form.title}}
  <button @click="readId">Read ID</button>
  <button @click="deleteForm">Delete</button>
</div>

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

https://i.sstatic.net/MNMEz.png

I need help getting the ID of the form clicked when the 'Read ID' button is clicked.

This information is necessary for deleting a particular form with

db.collection('forms').doc().delete()
.

Please let me know if further clarification is needed. I am open to edits and suggestions.

-edited- I apologize for the confusion in my previous explanation. I not only need the ID but also want to create a deletion functionality upon clicking the delete button associated with each form.

I will rephrase my question and repost it for better clarity.

Answer №1

If you need to retrieve the id of a newly created document, you can utilize the following code snippet:

const newDocRef = await db.collection('documents').add(
      {
        content: this.content
      }
    )

//get the id
console.log('id', newDocRef.id)

To acquire the id before adding any data, you can perform the following steps:

const reference = db.collection("documents").doc();
console.log('id', reference.id)

In case you require the id within a loop:

async generateContent () {
  const snapshot = await db.collection('documents').get()
  snapshot.forEach(doc => {
    const { content } = doc.data()
    console.log('id', doc.id) // id available in the loop
    this.documents.push({
      content
    })
  })

If you wish to delete form data by clicking on a button, first save the formID value and use it later for deletion:



methods: {
  async addDocument() {
    const newDocRef = await db.collection('documents').add(
      {
        content: this.content
      }
    )

  return newDocRef.id
  },
async removeDocument(id) {
   await db.collection('documents').doc(id).delete()
  }
}

Invoke the method like so:

await removeDocument(formID)

Answer №2

Within my application, I am able to utilize the following code snippet:

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

Based on that, I believe this solution should function as expected:

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

retrievedData.forEach(document => {
    const { title } = document.data()
    const identifier = document.id // <-- Important
    
    this.forms.push({
        title
    });
})

If you wish to remove a document when the "deleteform" function is triggered, the following approach would be appropriate:

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

// Initialization in created hook
async created () {
    const accessedData = await db.collection('forms').get();

    accessedData.forEach(doc => {
        const { title } = doc.data()
        const id = doc.id // <-- Vital
    
        this.forms.push({
            title,
            id,
        });
    })
}

// Functionality for deleting a document
async deleteform(docIdentifier) {
    await db.collection('forms').doc(docIdentifier).delete()
}

Trust this brings clarity to your issue!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The Flask server push appears to be functioning correctly, yet the EventSource.onmessage event is not triggering as expected

My implementation includes a route /stream that is designed to push the string 'test' every second. Upon accessing this URL (localhost:12346/stream) on Chrome, I observed that it opens a blank page and adds "test" to the page every second. This ...

Bring in Bootstrap and the Carousel plugin using Webpack Encore

Currently, I am tackling an issue within my Symfony project that involves Webpack Encore and the loading of Bootstrap and the Carousel plugin. The problem may stem from how I import Bootstrap, as it seems to partially work when I import the file like this ...

Is it possible to execute a REST call in JavaScript without utilizing JSON?

(I must confess, this question may show my lack of knowledge) I have a basic webpage that consists of a button and a label. My goal is to trigger a REST call to a different domain when the button is clicked (cross-domain, I am aware) and then display the ...

Utilizing deferred to ensure that one function completes before triggering a refresh

In my JavaScript code, I have an ajax call that receives a GUID from the server-side code in the response. After getting the GUID successfully, it is used to make a call to an iframe. The ultimate goal is to refresh the page once the iframe has completed i ...

Edit data with modal form in Angular-UI

Currently in the process of developing a single page todo application using AngularJs and Angular-Ui. Encountering difficulties when attempting to edit a todo item at this stage. The plan is to utilize a modal window for editing information, successfully ...

Having trouble with integrating Firebase and Vue database

While attempting to integrate Firebase with my Vue 4 application, I encountered the following error: Uncaught TypeError: db__WEBPACK_IMPORTED_MODULE_1_.default.database is not a function The versions I am using are: "firebase": "^9.0.0&qu ...

Connect a responsive div to a main div

I'm relatively new to the world of Javascript, CSS, and HTML. Currently, I'm attempting to anchor a div to the center and bottom of its parent div. The parent div contains a responsive background image and my fa fa-arrow icon is correctly positi ...

Adjustable page dimensions

I am attempting to achieve this task without relying on jQuery. My goal is to load a page where the content adjusts dynamically based on the dimensions of the browser window. I currently have two versions of the code, one with an image in the content div ...

The significance of using the Spread operator in React-Redux Reducers

Exploring the essence of the spread operator has been quite intriguing. Based on my interpretation of the documentation, it seems that the spread syntax essentially duplicates the existing object and then gets replaced by a new object when one is introduce ...

Modifying the value property of the parent element

Here is an example of the HTML code I am working with: <td value='3' style='text-align: center'> <select class='selection' onchange=''> <option value='1'>1</option> <opti ...

Retrieve the boolean value associated with a checkbox

I inherited a project from another developer. The code is able to retrieve data from the text input fields in the form, but not from the checkbox inputs. The previous developer implemented these functions (among others): protected function getObjectStrin ...

I developed a compact application utilizing Node.js in tandem with Express framework

There is an issue with the GPA calculator app built using Node.js and Express. It works fine for a single user, but when multiple users try to use it simultaneously, the scores are being combined, resulting in incorrect values. I need to create an app that ...

Encountered a 'Topology is closed' error while using EJS

After creating my profile.ejs page, I encountered an error upon reloading the page. Can someone help me understand what's causing this issue? Below is all the code I've used. My setup includes Node.js and Express as the server technologies. I cam ...

Tips for accessing the parent reference while binding using the .on() method

I needed to attach an event like this $("div").on("click", "li",function() { var div= $(this).parent().parent(); //this is what i'm using //..... }); above the <div> <ul> <li>1</li> <li>e2</l ...

Instructions for bringing the v-overlay element into view as soon as the page loads

Currently, I am in the process of developing an application using Nuxt v3.9.3 and Vuetify 3.5.1. I have incorporated the "absolute" link below into my implementation, which displays an overlay when a button is clicked. <template> ... <div id=&qu ...

Coldfusion: The Troubles of an Empty Link href="#" Error

For my CFWheels Coldfusion project, I have been utilizing Adobe Coldfusion Builder 3. In Coldfusion, when you want to output a variable, you typically do something like this: #variable_name# However, I am interested in incorporating an empty link into m ...

Following the submission of the ajax form, the page is reloading unexpectedly

I need the voting form on index.php to submit without refreshing the page and display results from an external page within index.php. HTML <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script&g ...

What is the best choice for UI design framework when creating an ERP web application?

I am in the process of creating a web-based ERP application using Angular Material. However, I've noticed that each input element takes up a significant amount of vertical space on the page. This means if I have 15 input elements, I have to scroll dow ...

if else statement fails to work in ajax-based login form

I tried to create the code below by referencing processes.php, submit form, and ajax from various sources on the internet. However, my code doesn't seem to be working properly. proccess.php <?php session_start(); ini_set('display_errors&apos ...

Provide net.socket as a parameter

What is the best way to pass the net.socket class as an argument in this scenario? Here's my code snippet: this.server = net.createServer(this.onAccept.bind(this)); this.server.listen(this.port); } Server.prototype.onAccept = function () { // Ho ...