Search code examples
javascriptnode.jsmongodbmongoose

Mongoose document delete automatically after one month


I just want to keep for one month after client-user will delete document particular document

so I decided to do fake delete and data showing in browser

my schema 
const product = new mongoose.Schema({ 
---
trash : { type: Boolean, default: false }
});

and I will show trash: false item only in browser ,Once user tried to delete then trash key will change to trash : true

I want to show these deleted ( trash : true) items under trash tab in browser and I want to automatically delete these trashed item after one month from DB

Solution

I know there is a solution by adding createdAt: { type: Date, expires: '1month', default: Date.now } in schema but this option works every item after one month from created date , I want to delete after one month from the change of trash : false to trash : true


Solution

  • Just create a new variable like trashedAt of type date, and then create TTL index with that as the key, as follows:

    db.products.createIndex({ "trashedAt": 1 }, { expireAfterSeconds: 30 * 24 * 60 * 60 })
    

    30 (days) * 24 (hours) * 60 (minutes) * 60 (seconds) = 1 month

    Then, while updating also mention trashedAt: new Date().

    db.products.updateOne(
       { 
          "someParameter": "someValue" 
       },
       { 
          $set: 
          { 
             "trash": true,
             "trashedAt": new Date() 
          } 
       }
    )
    

    or just remove trash completely from the document and use existence of trashedAt to show posts in Trash Tab, as follows:

    db.products.find(
    { 
       "trashedAt": 
       { 
          $exists: true 
       } 
    })
    

    TTL needs a date or timestamp to be used, so you can't do so without creating trashedAt: date.

    And if you add createdAt as the ttl index it will just delete the document one month after it was created.