0

In mongoose I can set the expiration of a document defining a column in this way:

expire_at: {
    type: Date,
    default: Date.now,
    expires: 7200
}

The code above will remove the record within two hours. How can I set the expire_at to a specific date?

sfarzoso
  • 1,356
  • 2
  • 24
  • 65

1 Answers1

1

You can set expires property readable string values like this:

For 1 minute:

 expires: "1m"

For 1 hour:

 expires: "1h"

For 1 day:

 expires: "1d"

But if you want to set a specific date, you can set the expires property 0, and set a date value to the field which has the TTL index as described in mongodb docs.

SuleymanSah
  • 17,153
  • 5
  • 33
  • 54
  • Yes, I can try, but how can I pass the expires parameter? I mean, when I create the object, ec: `let c = CarModel({expire_at: ???})` what I need to pass as value? thanks – sfarzoso Dec 30 '19 at 19:08
  • @sfarzoso hmm, it is not field but property, so I guess it is not possible to set a value from outside. – SuleymanSah Dec 30 '19 at 19:11
  • 1
    @sfarzoso I just guess like that, I am not sure. By the way there is also another option like this: default: () => new Date(+new Date() + 3 * 60 * 1000) //3 minutes – SuleymanSah Dec 30 '19 at 19:13
  • 1
    @sfarzoso maybe this [answer](https://stackoverflow.com/questions/59237955/how-to-remove-unverified-user-with-mongoose-and-ttl) also help a little. – SuleymanSah Dec 30 '19 at 19:14
  • 1
    @sfarzoso look what I found, it seems it is possible. https://stackoverflow.com/questions/24275117/how-can-i-set-the-ttl-date-on-document-creation-in-mongoose – SuleymanSah Dec 30 '19 at 19:16