Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Searching data older than a Date with typeORM

I am executing a query to Postgre DB to fetch data older than a specific date.

Here's my function

async filesListToDelete(): Promise<any> {
  return await this.fileRepository.find({
    where: { last_modified: { $lt: '2018-11-15 10:41:30.746877' } },
  });
}

Here's how I defined my File entity:

export class File {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ nullable: false })
  idFonc: number;

  @Column({ nullable: false })
  version: number;

  @Column('varchar', { length: 100, nullable: false })
  filename: string;

  @Column({ nullable: true })
  last_modified: Date;

  @Column({ nullable: false })
  device: boolean;

  @ManyToOne(type => Type, { nullable: false })
  @JoinColumn({ referencedColumnName: 'id' })
  type: Type;

  @OneToMany(type => FileDevice, filedevice => filedevice.file)
  fileDevice: FileDevice[];
}

I get this error

QueryFailedError: invalid input syntax for type timestamp: "{"$lt":"2018-11-15 10:41:30.746877"}"
like image 939
infodev Avatar asked Nov 27 '18 08:11

infodev


3 Answers

You can use MoreThan, the doc

async filesListToDelete(): Promise<any> {
  return await this.fileRepository.find({
   where: { 
       last_modified:  MoreThan('2018-11-15  10:41:30.746877') },
});}
like image 163
Nico.Wang Avatar answered Nov 19 '22 07:11

Nico.Wang


Also you can do this using createQueryBuilder as below:

    public async filesListToDelete(): Promise<any> {
        let record = await this.fileRepository.createQueryBuilder('file')
            .where('file.last_modified > :start_at', { start_at: '2018-11-15  10:41:30.746877' })
            .getMany();

        return record
    }
like image 41
Rishi1000 Avatar answered Nov 19 '22 07:11

Rishi1000


Either of these will fetch OLDER data

with built-in TypeORM operator (docs)

async filesListToDelete(): Promise<any> {
  return await this.fileRepository.find({
    where: { last_modified:  LessThan('2018-11-15  10:41:30.746877') },
  });
}

with PostgreSQL operator (docs)

public async filesListToDelete(): Promise<any> {
    let record = await this.fileRepository.createQueryBuilder('file')
        .where('file.last_modified < :start_at', { start_at: '2018-11-15  10:41:30.746877' })
        .getMany();

    return record
}
like image 37
grkmk Avatar answered Nov 19 '22 08:11

grkmk