2

I'm trying to create auto-expiring Mongoose document by setting expires.

const mySchema = new mongoose.Schema({
   title: {
      type: String,
      required: true
   },
   content: {
      type: String,
      required: true
   },
   expireAt: {
      type: Date,
      default: Date.now,
      index: { expires: 1200 } // Delete after 20 minutes.
   }
}, { collection: 'mycollection', timestamps: true });

I want it to terminate after 20 minutes but it keeps on terminating after about 1 - 2 minutes.

I've tried { expires: '20m' } as well which also deletes document after about 1 - 2 minutes.

passionateLearner
  • 722
  • 1
  • 7
  • 19
  • @goto1 I already tried ```20m``` format and same result. And I don't think it's in ms. Check this blog's step 2: https://dev.to/christopherliedtke/how-to-verify-your-users-email-addresses-node-js-express-dg0 – passionateLearner Dec 31 '20 at 21:07
  • Have you tried looking at this? [Setting expiry time for a collection in mongodb using mongoose](https://stackoverflow.com/questions/14597241/setting-expiry-time-for-a-collection-in-mongodb-using-mongoose) – goto Dec 31 '20 at 21:16
  • @goto1 Yes, I already did. They syntax I'm using will create same format. https://mongoosejs.com/docs/api.html#schema_Schema-index – passionateLearner Dec 31 '20 at 21:39
  • 1
    if you already created the index in this collection, you need to drop the index and recreate it in order for a "new/updated" expireAt index to take effect. – krisfremen Jan 01 '21 at 11:31
  • @krisfremen When I do ```console.log(mySchema.indexes());``` to see indexes, it logs this: ```[ { expireAt: 1 }, { expireAfterSeconds: 1200, background: true } ]```. – passionateLearner Jan 01 '21 at 11:46
  • strange, then it should work, the only thing I can think of.. if you are inserting the documents with a wrong time zone. Date.now() should give UTC time, but if your computer clock isn't set up correctly, this might put it in the future and mongod will delete these records in the next expiry batch. – krisfremen Jan 01 '21 at 12:12
  • @krisfremen I read many different blogs, documents, etc but I'm unable to fix it :(. I'm in EST timezone and my Mongodb outputs UTC. I also tried large time like ```1200000``` instead of ```1200``` and also ```'20m'``` format and all are deleting in 2 minutes. What do you mean by _'put it in the future and mongod will delete these records in the next expiry batch'_? – passionateLearner Jan 01 '21 at 12:29
  • yep, same problem document expire too quick even with large expiry, anyone have fix ? – KailasMM Jul 07 '21 at 12:02

0 Answers0