Search code examples
node.jspostgresqlnestjstypeorm

TypeORM - Entity Manager Date


I'm running into an issue with TypeORM with NestJS. The database being used is PostgreSQL. The TypeORM version I'm running is 0.2.45.

When I'm querying the database with Entity Manager with some complex queries the date output it's giving me a javascript date object in ISO format instead of "YYYY-MM-DD" in which it would if I was to query the database using find.

Running

const q = await this.invoicesRepository.find();
return q;

will return

[
  Invoice {
    ...
    date: '2022-04-01',
    dueDate: '2022-06-01',
    ...
  }
]

Where as running

const em = getManager();
const q: Invoice[] = await em.query('SELECT * FROM invoice');
return q;

will result in an output that looks like

[
  {
    ...
    date: 2022-03-31T13:00:00.000Z,
    dueDate: 2022-05-31T14:00:00.000Z,
    ...
  }
]

In the database the value is stored as date only adhering to YYYY-MM-DD format but it looks like TypeORM is trying to interpret the date value. Is there a way to make TypeORM not touch the formatting of the date?


Solution

  • You're running a raw query, so it's not TypeORM that's doing the conversion to a Date instance, but rather the Postgres driver.

    I'm not sure if it's possible to configure the driver not to perform the conversion, but a relatively simple workaround could be to force your time-related fields to a string:

    SELECT date::text AS dateString, dueDate::text AS dueDateString, * FROM invoice