Retrieve date(only) column as string or map to string without time using Prisma ORM

Viewed 4812

I'm using Prisma2 (prisma @prisma/client).

In my underlying postgres db I have a column of type date, i.e. date only without time.

Prisma returns for this column a Javascript Date object (https://www.prisma.io/docs/concepts/components/preview-features/native-types/native-types-mappings#datetime), which carries time information as well.

After serializing I end up with a full ISO string of date and time. However, I'd only like to return the date part (time part will always be 00:00:00).

At the moment I do:

return await prisma.entity.findMany().map(e => ({ ...e, date: e.date.toISOString().substring(0,10) }))

I'd like to get rid of the manual mapping as I have to repeat it for every query and the mapping gets more complicated for nested queries etc. pp.

Does Prisma support some kind of transformation (e.g. using class-transformer) that is added to the model (and automagically performed)? I haven't found anything in the docs. Or can I teach Prisma to return this column as a string, not a Date object?

2 Answers

Prisma Client is returning JavaScript Date objects by design, unfortunately this can not be configured in the Prisma Client API.

As a workaround, you could consider writing a middleware function that automatically converts Date objects to strings so that you don't need to do it manually in your application time every time you're working with a Date.

If you'd like to see this natively supported by Prisma, feel free to open a feature request with your use case so that our team can look into this.

you can use middware to retrieve a string, but if you do like this, your type of this field is still a "Datetime" in schema, which will limit your handles of this field using Datetime APIs!

Related