1

I am trying to create a TTL index in MongoDB. I read the answer on here, Answer which was very helpful.

The problem is that the documents just don't expire. Here's the code:

var AcThSchema = new mongoose.Schema({
    createdAt: {
      type: Date,
      expires: '1m',
      default: Date.now
    },
    key: {
      type: String,
      required: true,
      unique: true
    }
});

The weird thing that I did notice was that when I use the value 1 instead of Date.now as default for createdAt, the document does get deleted after a few seconds (probably the next time the mongo's TTL process runs)

Why is the document getting deleted for a default value of 1 but not for Date.now?

Sanjay S
  • 21
  • 3
  • 2
    Good you found a reference, but you need to read ALL the answers. Note this one; [*It is important to note that the TTL process runs once every 60 seconds so it is not perfectly on time always.*](https://stackoverflow.com/a/52563250/2313887). As for "default of 1", in BSON precedence `1` is **less than** the current milliseconds since epoch, which is what a BSON Date is stored as. – Neil Lunn Mar 05 '19 at 06:06
  • @NeilLunn I had gone through the answer that you have linked. But the problem isn't that the deletion is delayed by a few seconds, but that they aren't deleted at all. – Sanjay S Mar 05 '19 at 06:15

1 Answers1

0

The expires should be inside index. Like this

var AcThSchema = new mongoose.Schema({
createdAt: {
  type: Date,
  index: { 
    expires: '1m'
  },
  default: Date.now
},
key: {
  type: String,
  required: true,
  unique: true
}

});

Priidik Vaikla
  • 744
  • 4
  • 13