Search code examples
typescripttypeorm

How do I find the entity with the earliest date in typeORM


Basically, I have an entity with a date column, and I am trying to query for the entity with the earliest created date. I was wondering how I could find the earliest entity in typeORM.

I have something like this so far:

const latest_result = await getRepository(Verification).findOne({ where: {
    created_date: // Change to find latest date
}});

And my model looks like this:

export class Verification { 

    @Column({ nullable: false })
    success!: boolean

    @CreateDateColumn()
    created_date!: Date
};


Solution

  • I would do the easiest and straithforward way (but not optimized) by ordering DESC and taking the first one. Make sure to have an index on your date if the table as many records

    export class Verification { 
    
        @Column({ nullable: false })
        success!: boolean
    
        @Index()
        @CreateDateColumn()
        created_date!: Date
    };
    
    const latest_result = await getRepository(Verification).find({
       skip:0,
       take:1,
       order: { created_date: "DESC" }
    });