简体   繁体   English

Firestore 正在删除最后一个文档而不是我选择的文档

[英]Firestore is deleting the last document not the one I selected

I am trying to impelement a delete function in Firestore database and the problem is that when I click delete, it deletes the last document created, not the one that I want to delete.我试图在 Firestore 数据库中实现删除功能,问题是当我单击删除时,它会删除创建的最后一个文档,而不是我想要删除的文档。 This is how I get the data from the database:这是我从数据库中获取数据的方式:

db.collection("flights").get().then((snapshot) =>{ 
   snapshot.docs.forEach(doc => {
   var data = doc.data();
   var docID = doc.id;
   

And this is how I am trying to delete it:这就是我试图删除它的方式:

function deleteFlight(docID){
   firebase.firestore()
  .collection("flights")
  .doc(docID)
  .delete()
  .then(() => console.log("Document deleted")) // Document deleted
  .catch((error) => console.error("Error deleting document", error));
}

I want to specify that after I create a new document, the website is refreshed, so I think it loses somehow the document id.我想指定在创建新文档后刷新网站,所以我认为它以某种方式丢失了文档 ID。

In the comment section you have specified that you are calling the deleteFlight() function from a html button.在评论部分,您已指定从 html 按钮调用deleteFlight()函数。 As you are using forEach() loop after getting the collection of documents and within that populating docID , by the time the html button is clicked the forEach() loop would have been completed and then docID will have the document id of the document which comes last in ascending order because by default the documents are sorted in ascending order of document id as mentioned in this document .当您在获取文档集合并在该填充docID内使用forEach()循环时,当单击 html 按钮时, forEach()循环将已完成,然后docID将具有出现的文档的文档 ID最后按升序排列,因为默认情况下,文档按照本文档中提到的文档 id 的升序排序。 In your case I suspect the document id for the recently added document comes last when sorted in ascending order.在您的情况下,我怀疑最近添加的文档的文档 ID 在按升序排序时排在最后。 This is the reason the recently added document is getting deleted.这就是最近添加的文档被删除的原因。

I am not sure of your use case.我不确定你的用例。 But I would suggest you to declare a variable outside of the db.collection() method and implement some logic according to your use case to populate it with the document id which you want to delete.但我建议您在db.collection()方法之外声明一个变量,并根据您的用例实现一些逻辑,以使用您要删除的文档 ID 填充它。 Then use that variable in the deleteFlight() function.然后在deleteFlight()函数中使用该变量。

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

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