0

I'm creating an IOS Application where I've some discount codes and I would like them to expire after a specific date.

Is there any way I can automatically delete document which has expired?

Example: Let's say I create a discount code which should expire "2019-12-20 12:00", how can I delete this document when the time has passed? Is there any way to do this in Firestore? or can I compare current date with expiring date and remove it if it's older or equals to the time? If yes, how can I do this?

I've tried this so far:

                let expiring = data["expiring"] as? String

                let dateNow = Date()
                let dateFormatter = DateFormatter()
                dateFormatter.dateFormat = "dd-MM-yyyy HH:mm"
                let currentDate = dateFormatter.string(from: dateNow)

                let date = dateFormatter.date(from:expiring!)

                print(date, " ", currentDate)

But when I print it out the "date". returns "nil" and the currentDate returns the correct date. When I get both of them to return the correct value I would like to add an if-statement to check if "date" is older or equal to the correct date and time, and if that's the case, removing it.

Is there any easier way to do this? Like adding something in firestore to detect it automatically?

Do you know how to sort this up? Do you know how I can remove data when the date is older/equal to the expiring date?

Putte
  • 526
  • 1
  • 6
  • 15

2 Answers2

2

Firestore does not have any built-in ability to delete expired documents. If you want such documents to be deleted, you will have to build it yourself, or use one of the existing solutions.

But before deleting the expired documents, consider simply not showing expired documents in your application code by using a query, with something like this

self.db.collection("collection")
    .whereField("expiresAt", isGreaterThanOrEqualTo: startTimestamp)

With the above query your code will only read non-expired documents.


To delete expired documents, you'd run the inverse query. You can either run this from the application itself, but it is more common to run this in a server-side environment, such as in Cloud Functions.

There you'd:

  1. Run a query to determine all the expired documents.
  2. Loop over those documents.
  3. Delete them one by one with the code shown in deleting documents.

Also see:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
2

I have created a function that is scheduled every day @ 12:00 AM, to run on cloud functions.

// Delete messages previous than 3 days automatically from firestore.
// The job is schedules and will run daily on 12:00 AM
// .schedule("* * * * *") // Use (all starts) to run every 60 seconds.
// A minimum time for a cloud function possibly run.

exports.deleteOlderMessages = functions.pubsub
  .schedule("00 12 * * *")
  .onRun(async (context) => {

    const CUT_OFF_TIME = 72 * 60 * 60 * 1000; // 72 Hours in milliseconds.

    const date = Date.now() - CUT_OFF_TIME;
    // My Object in firstore is stored as Timestamp Object (class from Firebase)
    const timestamp = admin.firestore.Timestamp.fromMillis(date);

    // Query all documents ready to perform
    const query = admin
      .firestore()
      .collection("messages")
      .where("metadata.createdAt", "<=", timestamp);

    const messages = await query.get();
    messages.forEach((snapshot) => {
      snapshot.ref.delete();
    });
    console.log("Messages deleted");
  });
Usama Karim
  • 1,100
  • 4
  • 15