简体   繁体   中英

How can I simultaneously in one "click" event delete two documents from two collection in my cloud firestore?

i just want to delete multiple documents from two different collections(hive and entry). how should i do this? with two promises or how?

my below code works but the moment I add "location.reload()" anywhere, only the clicked hive is deleted. the page just doesn't work with this refresh function...

please help... thanks in advance!

    deleteBtn.addEventListener('click', (e) => {
      let id = e.target.parentElement.parentElement.getAttribute('data-id');
      var x = confirm("Deleting a hive will delete all its records.  Click 'Ok' to delete and 'Cancel' to return.");
      if(x){
// delete clicked hive
        db.collection('hive').doc(id).delete()
          .then(function () {
          })
          .catch(function (error) {
          })
// delete all entries from within clicked hive
        var deleteEntry = db.collection('entry').where('hive_id', "==", id);
        deleteEntry.get()
          .then(function(querySnapshot) {
            querySnapshot.forEach(function(doc) {
            doc.ref.delete()
            });
          })
          .catch(function (error) {
          })
      }else{
      }
    })

the above approach might be completely wrong and not clean...so i will just type my needed results here...

after clicking deleteBtn and confirming the delete, the clicked hive should be deleted and all entry records from that hive should also be deleted. the page needs to refresh and show that the hive is gone. (note that all entry records have the same hive will have the hives id as property)

THANKS!

That looks like a typical async problem. Try this: Add the delete code for entry collection inside the promise of deleting hive code.

   deleteBtn.addEventListener('click', (e) => {
   let id = e.target.parentElement.parentElement.getAttribute('data-id');
   var x = confirm("Deleting a hive will delete all its records.  Click 'Ok' to   delete and 'Cancel' to return.");
   if(x){
   // delete clicked hive
    db.collection('hive').doc(id).delete()
      .then(function () {

   // delete all entries from within clicked hive
    var deleteEntry = db.collection('entry').where('hive_id', "==", id);
    deleteEntry.get()
      .then(function(querySnapshot) {
        querySnapshot.forEach(function(doc) {
        doc.ref.delete()
        });
      })
      .catch(function (error) {
      })

      })
      .catch(function (error) {
      })

  }else{
  }
})

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