typescriptmikro-orm

MikroORM: How to query a date property by the day or month and not the full date?


I have a entity with a date property

@Entity()
export class Foo {
    // ...other properties

    @Property({ type: DateType })
    date = new Date()
}

And I want to make a query to find all Foo that are from some specific day.

e.g.

async getByDate(someDate: Date) {
    const foo = await this.repository.find({
        // What should go to get Foo from the same day as `someDate` ?
    })
}

I couldn't find in the documentation how to do it.

I would also like to do things like "find Foo from some week" or "find Foo from from some month"


Solution

  • Note that v6 changed the DateType to map to a string instead.

    If you use the DateType, you are mapping it to the Date object, so you should query by Date objects. The time part of the Date object will be truncated - that happens in the DateType so feel free to check its source code, it's quite straightforward.

    const users = await em.find(User, { date: new Date('2020-05-20') });
    

    https://github.com/mikro-orm/mikro-orm/blob/master/packages/core/src/types/DateType.ts

    From the implementation you can also see that in fact it does support querying by strings too, so this will work as well:

    const users = await em.find(User, { date: '2021-04-20' });
    

    To filter for a whole week, you need to first find the start and end of the week (will keep that for you), and use combination of $gte and $lt operators:

    const users = await em.find(User, {
      date: {
        $gte: new Date('2021-04-19'), 
        $lt: new Date('2021-04-25'),
      },
    });
    
    
    // or with strings
    
    const users = await em.find(User, {
      date: {
        $gte: '2021-04-19',
        $lt: '2021-04-25',
      },
    });