[英]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.