Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

remove selected firebase data according to condition onload

I am trying to delete data that will meet the condition I set. That is, once the ‘Deadline’ passed today’s date, they must be deleted.

This is my realtime database
enter image description here

This my code to get the current date and compare it to the deadlines in the db

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

// get today's date
let today = new Date();
let dd = String(today.getDate()).padStart(2, '0');
let mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
let yyyy = today.getFullYear();

today = yyyy + '-' + mm + '-' + dd;
let now = today.toString();

function deadlineLimit(){

    const q = query(ref(db, "subjects/MMW/"));

    get(q).then((snapshot)=>{

        snapshot.forEach(function(childSnapshot) {
            var deadlines = childSnapshot.val();
            var dbDates = deadlines["Deadline"];

            // if deadlines in database < date today
            if (dbDates < today){
                let expiredDeadline = childSnapshot.val().Deadline;
                console.log(expiredDeadline + " Must be removed");          // Must be deleted

                // CODE HERE to remove all data that met the condition
            }
        })
    });
}

deadlineLimit();    // call this function

I am able to get the deadlines past todays date, but how can i delete them?

>Solution :

You can use the remove() function to delete those nodes as mentioned in the documentation:

get(q).then(async (snapshot) => {
  const deletePromises = [];

  snapshot.forEach((childSnapshot) => {
    var deadlines = childSnapshot.val();
    var dbDates = deadlines["Deadline"];

    if (dbDates < today) {
      // push to promises array
      deletePromises.push(remove(childSnapshot.ref))
    }
  })
  
  await Promise.all(deletePromises);
  
  console.log("Data deleted")
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading