Search code examples
mongodbtypeorm

Setting expiration TTL on MongoDB collection


How do you set ttl expiration using Typeorm with a mongoDB collection? I would like to have the records removed automatically and this is easy to do with mongoose, but I can't figure out how it's done using TypeOrm.

In mongoose it's done like this

const Schema = mongoose.Schema;

const YourSchema = new Schema({
 expireAt: {
   type: Date,
   default: Date.now() + 10 * 60 * 1000   // expires in 10 minutes
 },
});

this is my entity code I tried, but it fails with an unknown error.

import { Column, CreateDateColumn, Entity, Index, IndexOptions, ObjectID, ObjectIdColumn, Repository, UpdateDateColumn, getConnection } from 'typeorm'

import uuid from 'node-uuid'

const indexOpts: IndexOptions = {
  expireAfterSeconds: 10 * 60 * 60, // expires in 10 minutes,
}

@Entity()
export class RefreshToken {
  @Index(indexOpts)
  @ObjectIdColumn()
  public id!: ObjectID

  @CreateDateColumn()
  public createdAt!: string

  @UpdateDateColumn()
  public updatedAt!: string

  @Column()
  public userId!: string

  @Column()
  public token: string = uuid.v4()
}

Update thanks to @Jijo_Alexander I have added the following

export const getRefreshTokenModelRepo = async (): Promise<MongoRepository<RefreshToken>> => {
  const repo = getMongoRepository(RefreshToken)
  const expireAfterSeconds = 600 // 60 * 60 * 24 * 30
  await repo.createCollectionIndex('refreshTokenExpireIndex', { expireAfterSeconds })
  return repo
}

But the records added will not auto delete. So maybe I am missing something with how indexes work in mongodb


Solution

  • You can try with createCollectionIndex

    getConnection.createCollectionIndex(RefreshToken, "public", { expireAfterSeconds: 600 }); //  expires in 10 minutes
    
    • The indexed field must be BSON date type or an array of BSON dates
    • If the indexed field in a document is not a date or an array that holds a date value(s), the document will not expire.
    • If a document does not contain the indexed field, the document will not expire.