简体   繁体   中英

How to get the document id of the document on which user clicks?

JS:

function getDataOfBus() {
   var dates = document.getElementById('departure-date').value.toString();
   var fromd = document.getElementById('from-dest').value.toString()
   var tod = document.getElementById('to-dest').value.toString()
   console.log(dates + " -" + fromd + " -" + tod)

   db.collection('Buses').where("DepartureDate", "==", dates).where("To", "==", tod).
   where("From", "==", fromd).get().then((snapshot) => {
      let html = '';
      snapshot.forEach((busDatas) => {
         busData = busDatas.data()
         console.log(busData.id)
         html += `
           <div class="single-room-area d-flex align-items-center mb-50 wow fadeInUp" data-wow-delay="100ms" id="prince">
            <div class="room-thumbnail">
                <img src="${busData.ImageLink}" alt="">
            </div>
            <div class="room-content">
                <h2><a href="javascript:setImage();">${busData.TourName}</h2>
                <h6>${busData.From} to ${busData.To}</h6>
                <h4>₹ ${busData.SeatPrice} </h4>
                <div class="room-feature">
                    <h6>Boarding Point  <span>${busData.BoardingTime}</span></h6>
                    <h6>Dropping Point <span>${busData.DroppingTime}</span></h6>
                    <h6>Seats Left <span>${busData.SeatsLeft}</span></h6>
                    <h6>Total Time <span>${busData.TotalTime}</span></h6>
                    <h6>Departure Date <span>${busData.DepartureDate}</span></h6>
                </div>
            </div>
           </div>
         `

         document.getElementById('bus-container-dynamic').innerHTML = html;
      }) // End foreach
   }) // End then

}

function setImage() {

}   

I have performed the above code to display the documents from the cloud Firestore. But i am not getting how to get that document id of that document on which the user clicks and use that document id in setImage() function?

By doing busData = busDatas.data() you are assigning the object returned by the data() method to the busData variable, but this object does not contain the doc ID.

You should either use another variable to hold this value or assign the document ID to this busData object. The following (implementing the second option) should do the trick:

snapshot.forEach((busDatas) => {

    var busData = busDatas.data()
    busData.docId = busDatas.id
    //...

    <h2><a href="javascript:setImage('${busData.docId}');">${busData.TourName}</h2>
    //...

});

busDatas (with an s) is a QueryDocumentSnapshot and you use its id property.


You could also use the spread syntax , as follows:

var busData = { docId: busDatas.id, ...busDatas.data() }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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