What's the best way to have a field for a date in PostgreSQL and TypeORM?
I'm relatively new in PostgreSQL (in general SQL database), but in MongoDB (with Mongoose) I usually have a field like this:
export class User {
@Prop({ default: Date.now() })
createdAt: Date;
}
What would be the equivalent to this in TypeORM and PostgreSQL? Because, if I use this approach, PostgreSQL throws me an error.
QueryFailedError: date/time field value out of range: "1634416004545"
I know it's an old one, but it's one I stumbled on today and with no approved answer, so I thought it could be of help to someone like me in the future.
Basically, the problem comes from using Date.now() instead of new Date(). My working example looks like this
@Column({ type: "timestamptz", default: () => "CURRENT_TIMESTAMP" })
createdDate: Date;
If the value is not provided, it will assign the current value. Note here that if you update a row and the new value misses the createdDate field, the old one will be overwritten.
Then if you want to set it manually, you simply use new Date() like this
const created = { ..., createdDate: new Date(), ...}
You can use the @CreateDateColumn decorator to archieve what you want:
export class User {
@CreateDateColumn()
createdAt: Date;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With