Error encountered in Mikro-orm migration when handling a date property mapped as a string field type

I encountered an issue with the createdAt property while using graphql, typescript, mikro-orm and postgresql for implementing CRUD operations on posts:

DriverException: alter table "post" alter column "created_at" type timestamptz(0) using ("created_at"::timestamptz(0)); - cannot cast type jsonb to timestamp with time zone

Here is the entity definition for the createdAt property:

@Field(() => String)
@Property({ type: "date" })
createdAt = new Date();

Additionally, these are the migration snippets generated from the createdAt entity:


    this.addSql('alter table "post" drop constraint if exists "post_created_at_check";');
    this.addSql('alter table "post" alter column "created_at" type timestamptz(0) using ("created_at"::timestamptz(0));');

How can I resolve this error? What changes should I make to fix it?

Answer №1

After extensive troubleshooting, I managed to resolve the issue at hand. Before proceeding, I would like to extend my gratitude to the developer of Mikro-orm for their assistance.

In a bold move, I opted to delete the existing database and create a fresh one from scratch. Despite this effort, the problem persisted, leading me to discover that there were some bugs in the yarn tsc -w command. To rectify this, I had to remove the dist folder and rerun the mentioned command.

Subsequently, I encountered a new set of errors. Initially, I attempted to replace type timestamptz(0) with type String; however, it soon became clear that my understanding of data types was lacking.

After conducting further research, I made adjustments to the types as follows:

    this.addSql(`CREATE TABLE "post" ("id" SERIAL NOT NULL, "title" character varying NOT NULL, "createdAt" TIMESTAMP NOT NULL DEFAULT now(), "updatedAt" TIMESTAMP NOT NULL DEFAULT now())`);

Answer №2

The current column in Postgres is set as jsonb. To convert it to datetime, you cannot do so directly. You must first drop the column and then add it again with the new data type.

To make this change, you can update your migration file by removing the column and adding it back in, or if you're unsure how to write the necessary queries, consider deleting the existing migration, commenting out the property, creating a new migration to drop the column, executing it, and then uncommenting the property and generating another migration to add it correctly.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to optimize TypeScript's array type inference algorithms

My dilemma revolves around defining a type/interface for a collection of properties where each property has a specified type. You can reference Props in the code snippet below for clarification. The goal is to create a type that represents a tuple <A, ...

Attempting to retrieve data either by code or with a WHERE condition proves unsuccessful as the data retrieval process yields no results

Seeking assistance with my Angular project that is utilizing a Node.js server and MSSQL express. I am having trouble retrieving data using a WHERE condition in my code. Any help in identifying the missing piece or error would be appreciated. Thank you. // ...

What is the best method for merging multiple Files (as File[]) into a single Blob?

Is it possible to send a POST request with a form-data body using Postman, along with the following key-value pairs? https://i.sstatic.net/VC2LYMkt.png When attempting to include multiple files, designated as File[], within a single Blob (as shown in the ...

Encountering issues with Sequelize Typescript on delete cascade functionality

One issue I encountered is related to the FK relationship between Group and GroupAttendee. Whenever I try to call Group.destroy(), a foreign key constraint failure exception regarding the GroupAttendee entries pops up. I know how these constraints work at ...

Setting Timezones in Typescript

I am working on a React application that fetches data in ISO8601 format, specifically timestamps from US/Chicago time like this example: "2020-09-01T06:05:00-05:00." I suspect it's US/Chicago because of the -05:00 indicating central daylight savings t ...

Angular ngFor not displaying the list

I'm encountering an issue with my HTML page where I'm using NGFor with an array. The error message I receive is as follows: landingpage.component.html:142 ERROR Error: Cannot find a differ supporting object '[object Object]' of type &ap ...

The ordering of my styles and Material-UI styles is causing conflicts and overrides

Greetings fellow developers! I'm currently facing an issue with my custom styles created using makeStyles(...). The problem arises when I import my styles constant from another module, and the order of the style block is causing my styles to be overr ...

What is the best way to convert an Express route to Typescript?

I'm trying to create a wrapper called loginRequired for my Express route, but I'm struggling to define the right types. This is what my loginRequired wrapper looks like: export const loginRequired = (fn) => (req, res, next) => { // Ch ...

Converting "promises" to "string" using static methods in TypeScript

I am struggling with incorporating "promises" into my TypeScript code. I am currently developing an e2e testing framework using Protractor and TypeScript, and I need to make database queries to retrieve data for filling forms or performing validations. To ...

Compare one set of words to another set by counting the number of matches and organizing them by the level of similarity

I am looking to compare user input with a string column, both of which contain space-separated words. The sort criteria includes: number of words matched from the beginning (prefix match) descending number of words matched descending columns where match ...

Why is the function not being called when declaring a variable, resulting in a type error?

click here reference: const fn1 = (arg1: { key: number, })=>{ console.log(arg1) } fn1({ key: 1 }) const data = { key: 1, a: 1, } fn1(data) fn1({ key: 1, a: 1, }) more info Assistance needed: Why is ...

Leveraging ES Module packages in Azure TypeScript Function Development

I'm encountering an issue while trying to utilize the p-map package in my Azure Function. The error message that I'm getting is as follows: A Worker failed to load function: 'serverless' with function id: '<id>'. Result: ...

A step-by-step guide on extracting information from a component and using it within a Guard

A challenge I am facing is how to display a warning prompt on the screen if the user tries to leave a page after making changes to a form. I have successfully created a Guard that logs a message to the console when the user attempts to navigate away from t ...

Processing and transforming a TypeScript object results in an unexpected outcome

I have received an object that has the following structure: {\"key1\":{\"cluster_region\":\"centralus\"},\"key2\":{\"cluster_region\":\"westeurope ...

Guide to assigning object values according to properties/keys

I'm currently diving into Typescript and exploring how to dynamically set object types based on specific keys (using template literals). Check out the code snippet below: interface Circle { radius: number; } interface Square { length: number; } ...

Issue with the code flow causing nested function calls to not work as expected

I'm experiencing an issue with my code: The problem arises when param.qtamodificata is set to true, causing the code to return "undefined" due to asynchronous calls. However, everything works fine if params.qtamodificata is false. I am seeking a sol ...

Custom groupBy function for arrays in TypeScript

Below is an example of an array: [ { "exam" : "1", "class": "1A1", "rooms": "245", "teachers": "A" }, { "exam" : "1", "class" ...

Is it best practice to declare a variable only once PRIOR TO rendering in a

In React, I am trying to access the height of a div by using useRef and store it in a variable called defaultHeight. const jselectRef = useRef<HTMLButtonElement>(null) let defaultHeight: number | undefined console.log(defaultHeight) // returns und ...

Unexpected Error with Angular Abstract Class Definition

I've encountered a peculiar Type Error while working with Abstract Classes in Angular 16. Error: Uncaught (in promise): TypeError: this.httpService.get is not a function Could it be that my interpretation of using Abstract Classes is off? Everythin ...

Trying to access the 'cpf' property of an undefined value is causing an error

I have a file that I'm using to create an object to store in my Firestore database. The file is imported into my register page, and I'm using ngModels to capture user-input values. To achieve this, I've initialized my data object inside the ...