Home > Blockchain >  remove selected firebase data according to condition onload
remove selected firebase data according to condition onload

Time:07-11

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

// 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?

CodePudding user response:

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")
});
  • Related