skip to Main Content

I am currently using Nest’s SchemaFactory to setup my MongoDB models. Here is a link to their documentation:
https://docs.nestjs.com/techniques/mongodb#mongo

I was wondering how I could set a TTL index using this abstraction. I want every instance of a specific model to delete after 15 minutes.

2

Answers


  1. The documentation that you linked has the following section:

    Alternatively, the @Prop() decorator accepts an options object argument (read more about the available options). With this, you can indicate whether a property is required or not, specify a default value, or mark it as immutable. For example:

    @Prop({ required: true })
    name: string;
    

    Taking a look at the Mongoose docs, there is a special option for Date types, expires. This leads me to believe you could create a TTL index by including a Date field like so:

    @Prop({ expires: 900 }) // `expires` is in seconds
    timestamp: Date;
    
    Login or Signup to reply.
  2. @Schema({})
    export class Test {
      @Prop({ type: Date, expires: 900, default: Date.now })
      createdAt: Date;
    }
    

    Or:

    @Schema({ timestamps: true })
    export class Test {
      // ...
    }
    
    export const TestSchema = SchemaFactory.createForClass(Test);
    TestSchema.index({ "createdAt": 1 }, { expireAfterSeconds: 900 });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search