简体   繁体   English

无法在 Firebase 中获取文档 ID

[英]Unable to get doc id in Firebase

I am trying to get the doc id of each data entry upon click to delete that specific record, but upon checking it is only showing id of the first entry made in the Firebase.我试图通过单击删除该特定记录来获取每个数据条目的文档 ID,但在检查时它只显示 Firebase 中第一个条目的 ID。

const deleteRecord = () => {
  db.collection("records").onSnapshot((querySnapshot) => {
    querySnapshot.forEach((doc) => {
      // console.log(doc.id)
      let recToDel = document.querySelectorAll(".records")
      for (let toDelRecord of recToDel) {
        toDelRecord.onclick = () => {
          console.log(doc.id)
        }
      }
    })
  })
}

The loops are nested, so the last iteration of the querySnapshot.forEach loop is the one that sets the same doc.id for every recToDel dom element.循环是嵌套的,因此querySnapshot.forEach循环的最后一次迭代是为每个recToDel dom 元素设置相同的 doc.id 的迭代。

Fix by looping just one collection and indexing into the other...通过仅循环一个集合并索引到另一个集合来修复...

    let recToDel = Array.from(document.querySelectorAll(".records"));
    querySnapshot.docs.forEach((doc, index) => {
      if (index < recToDel.length) {
        let toDelRecord = recToDel[index];
        toDelRecord.onclick = () => {
          console.log(doc.id)
        }
      }
    });

If there are fewer .records elements than there are docs, some won't be assigned.如果.records元素少于文档,则不会分配一些元素。

Doing this onSnapshot will cause these assignments to be made every time the collection changes, including on deletes.在快照上执行此onSnapshot将导致每次集合更改时(包括删除时)都进行这些分配。 If that's not your intention, fix by changing to get() .如果这不是您的意图,请更改为get()进行修复。

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

相关问题 我正在尝试编写代码以从 Firebase 获取(文档 ID) - Im trying to write code to get (doc id) from Firebase Firebase 获取嵌套多个分支的文档 ID - Firebase get doc ID that is nested several branches up React中如何获取Firebase 9中的多个Doc对象? 并使用其文档 ID 从 firestore 获取多个文档? - How to get multiple Doc objects in Firebase 9 in React? and get multiple docs from firestore using its doc id? 获取自动生成的文档 ID 以创建文档或更新文档 Firestore / Firebase 中的数组的更好方法 - Better way to get document ID which was auto generated to create the doc or update an array inside the document Firestore / Firebase 如何从 firebase 获取单个文档信息? - How to get a single doc info from firebase? 访问 doc.id in.onWrite firebase 云 function - accessing doc.id in .onWrite firebase cloud function 如何在 firebase 9 中使用批处理创建自动生成的文档 ID? - how to created autogenerated doc id using batch in firebase 9? Firebase V9 - 创建时自定义“文档 ID”(Javascript) - Firebase V9 - Custom 'Doc ID' Upon Creation (Javascript) 通过端点将文档 ID 的 firebase 集合作为数组发送 - send a firebase collection of the doc id's as an array through an endpoint 获取firebase文档的ID - Get the ID of firebase document
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM