0

I'm trying TLL in MongoDB schema. I know I can hard code a TLL index in the schema, for example, 60. And this object will get removed from the database after 60 seconds. But I'm thinking about a scenario in that I let the user decide how long an object created by him will last in the database. For example, the user is posting a question. And the user wants to decide how long this question will be live on the website, for example, 15 days or 30 days or whatever he wants. So, I cannot hard code a TLL index. Can someone tell me if there's a way I can use a variable for TLL or if there's a better to do this task? Thank you. Below is the code for the schema I have for now.

const questionSchema = new mongoose.Schema({

question: {
    type: String,
}

}, {timestamps: true});

ratingSchema.index({createdAt: 1},{expireAfterSeconds: 60});

1 Answers1

0

In Mongoose, you create a TTL index on a Date field via the expires property in the schema definition of that field:

// expire docs 3600 seconds after createdAt
new Schema({ createdAt: { type: Date, expires: 3600 }});

Note that:

  1. MongoDB's data expiration task runs once a minute, so an expired doc might persist up to a minute past its expiration.

  2. This feature requires MongoDB 2.2 or later.

  3. It's up to you to set createdAt to the current time when creating docs, or add a default to do it for you as suggested here

{ createdAt: { type: Date, expires: 3600, default: Date.now }}

  • Thanks. But I meant is that possible to let the user decide the value for 'expires' when an object is created. For example, can I do something like createdAt.expires = {userInputValue} – Benjamin Seang Feb 25 '22 at 02:16