简体   繁体   中英

Delete document in firestore when value of document matches

Im having a bunch of documents in a collection in firestore. What I want to archieve is to search the documents by a "timestamp" property, after that I want to delete exactly this document.

My code looks right now like this:

firebase.firestore().collection("chatrooms").doc(`${chatId}`).collection(`${chatId}`).where("timestamp", "==", timekey).get().then((QuerySnapshot) => {
                if (!QuerySnapshot.empty) {
                    QuerySnapshot.forEach((doc)=>{
                        console.log(doc.data().value)
                    });
                } else {
                    // doc.data() will be undefined in this case
                    console.log("No such document!");
                }
            });

It is not deleting anything yet, its only returning me the value of the found document in my collection so I can see if the .where() call even works. Im having trouble to combine this .where() together with .delete() and I am not even sure if that is possible. Does anybody have any idea how to accomplish this task?

I can't see .delete() in your code. Also you cannot combine .delete() and .where() . You need the document IDs or the references to them. You can try this:

firebase.firestore().collection("chatrooms").doc(chatId).collection(chatId).where("timestamp", "==", timekey).get().then((QuerySnapshot) => {
  if (!QuerySnapshot.empty) {
    const deleteDocs = []
    QuerySnapshot.forEach((doc)=>{
      console.log(doc.data().value)
      deleteDocs.push(doc.ref.delete())
    });
    Promise.all(deleteDocs).then(() => {
      console.log("Docs delete")
    }).catch(e => console.log(e))

  } else {
    // doc.data() will be undefined in this case
    console.log("No such document!");
  }
});

PS: You don't need to use Template Literals [ ${} thing] if you just have one variable. You can directly pass the var as .doc(chatId)

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