Home > database >  Delete Firebase document after 30 minutes
Delete Firebase document after 30 minutes

Time:04-10

I want to delete some documents in Firebase 30 minutes after creation. I'm trying to use Firebase Functions for this. Somehow it always deletes documents without checking the dates. Here is my code. It's working but I don't understand why can't I check the dates.

exports.scheduledFunction = functions.pubsub.schedule('every 1 minutes').onRun((context) => {
  const now = new Date();
  const queryTime = new Date(now - 30 * 60000);

  const trips = admin.firestore().collection('trips');
  const allTrips = trips.get().then(snapshot => {
    snapshot.forEach(trip => {
      if (trip.data().date < queryTime) {
        admin.firestore().collection('trips').doc(trip.id).delete();
      }
    });
  });

  return allTrips;
});

CodePudding user response:

The variable now is a Date and not a number. Try using Date.now() to get current timestamp instead:

const queryTime = new Date(Date.now() - 30 * 60000);

Then you can use where() clause to get documents where date field is older than 30 minutes instead of fetching all documents and filtering them out yourself. This will save many read charges as you are fetching matched documents only and not the whole collection.

export const scheduledFunction = functions.pubsub
  .schedule("every 1 minutes")
  .onRun(async (context) => {
    // async fn ^^
    const queryTime = new Date(Date.now() - 30 * 60 * 1000);

    // Alternatively:
    // const queryTime = admin.firestore.Timestamp.fromMillis(Date.now() - 30 * 60 * 1000);

    // Query to fetch documents where date is less than queryTime
    const tripsQuery = admin
      .firestore()
      .collection("trips")
      .where("date", "<", queryTime);

    const allTrips = await tripsQuery.get();
 
    // Mapping an array of delete promises
    await Promise.all(allTrips.docs.map((d) => d.ref.delete()));

    return allTrips;
  });

Alternatively you can also use batched writes to delete up to 500 documents at once.

  • Related