Home > OS >  How can I define a TTL index on a MongoDB schema using NestJs
How can I define a TTL index on a MongoDB schema using NestJs

Time:07-05

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.

CodePudding user response:

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;

CodePudding user response:

@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 });
  • Related