Using TypeORM with a timestamp type column set to default null can lead to an endless loop of migrations being

In my NestJs project using TypeORM, I have the following column definition in an entity:

@CreateDateColumn({
    nullable: true,
    type: 'timestamp',
    default: () => 'NULL',
    })
public succeededAt?: Date;

A migration is generated with the correct structure:

export class migration123 implements MigrationInterface {
   name = 'migration123';

   public async up(queryRunner: QueryRunner): Promise\<void\> {
      await queryRunner.query(
         `CREATE TABLE [...], "succeededAt" TIMESTAMP DEFAULT NULL, [...]`
   );
   \[...\]
}

However, when I try to generate a new migration with TypeORM CLI after running this migration, it still detects differences:

[...]
public async up(queryRunner: QueryRunner): Promise<void> {
        await queryRunner.query(`ALTER TABLE "mercadopago_payment_request" ALTER COLUMN "succeededAt" SET DEFAULT null`);
[...]

It seems that Postgres treats null as the default value globally and doesn't require a specific rule for it. This confuses TypeORM, leading to unnecessary adjustments.

Do you have any suggestions on how to resolve this issue?


I attempted to remove the default value altogether:

@CreateDateColumn({
    nullable: true,
    type: 'timestamp',
    })
public succeededAt?: Date;

However, this change results in a migration setting the default value to now():

export class migration123 implements MigrationInterface {
   name = 'migration123';

   public async up(queryRunner: QueryRunner): Promise\<void\> {
      await queryRunner.query(
         `CREATE TABLE [...], "succeededAt" TIMESTAMP DEFAULT now(), [...]`
   );
   \[...\]
}

I specifically need to set null as the default value, hence the initial configuration.

Answer №1

The issue I encountered stemmed from using the @CreateDateColumn decorator.

To resolve this, I switched to using a standard date column:

  @Column({ nullable: true, type: 'timestamp' })
  @IsDate()
  public succeededAt: Date | null;

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

The process of passing request parameters using the GET or POST method in Node.js

I'm struggling to retrieve the data server-side in my node.js application. As a newcomer to node.js, I'm using express. When inspecting the request in the developer console, it appears as id=Bharadwaj&title=requestcheck! <!DOCTYPE html> ...

What is the best way to implement a hover delay for an element in Angular?

Here is an element I'm working with: <div (mouseenter)="enter()" (mouseleave)="leave()">Title</div> In my TypeScript file: onHover = false; enter() { this.onHover = true; // additional functionality... } leav ...

I am unable to utilize Local Storage within NextJS

type merchandiseProps = { merchandises: merchandiseType[]; cart?:string, collection?:string, fallbackData?: any }; const MerchandiseList: FC<merchandiseProps> = ({ merchandises }) => { const [cart, setCart] = useState<merchandiseType ...

I am currently experiencing an issue with inserting all documents from an Excel file into my database, as the last row is not getting inserted. Can anyone offer guidance on

Hi there, I am facing an issue where the last row of my Excel file is not getting inserted into the database. Despite logging every step, it seems that the end event is firing before the data event. Can someone help me fix this problem and provide ideas to ...

Obtain an assortment and append a new element to the output

I am trying to create a function in the Server script that can return a collection along with an additional value. For example: Meteor.publish("users", function () { var users; users = Meteor.users.find(); users.forEach(function (user){ ...

Extend the express request object with Typescript and then export the modified object

Seeking to enhance the Request object from express with custom fields using typescript. Based on this particular source, I created a file named @types/express/index.d.ts containing the following code : import { MyClass } from "../../src/MyClass" ...

The issue of receiving undefined in NodeJs while using $not with MongoDB

I'm attempting to create a find command in MongoDB using $not as shown in this link, await Match.find( { type:"Friendly", status:"Pending", "date.fullDate":{$gt: date}, $not:{$or: [{"team1.players":{$elemMatch: {_id:player ...

Struggling to retrieve posted data using Angular with asp.net

I have encountered an issue while sending a post request from Angular to my ASP.NET server. I am trying to access the values of my custom model class (SchoolModel) and I can see that all the values are correct inside Angular. However, when I attempt to ret ...

Discover information based on attribute value with MarkLogic

I am working on a MarkLogic 8 database and I have the following code snippet: declareUpdate(); var book0 = { id: fn.generateId({qwe: 'book'}), username: 'book', password: 'pass' }; var book1 = { id: fn.generateId({asd ...

Troubleshooting issues with rendering views in AngularJS, Express, and NodeJS

I'm currently exploring Angularjs and attempting to build a basic one-page application using ngRoute. However, I've encountered an issue. I want my users to always be directed to the index.html file no matter what, but when the URL is /page1 my s ...

Higher order components enhance generic components

I'm facing an issue where I want to assign a generic type to my React component props, but the type information gets lost when I wrap it in a higher order component (material-ui). How can I ensure that the required information is passed along? type P ...

What is the reason for the shift to a different command-line interface when executing a node file?

I've been trying to set up a node.js server, but for some reason, it's not running my server file. Here is the code for the server file: const express = require('express'); const app = express(); const PORT = 3000; app.use(express.json( ...

What could be the reason why my cookies are not getting set in Node.JS when using cookie-parser?

Recently, I have been working on a project with Node.JS and trying to set a cookie based on an ID passed as a GET variable. The code was functioning properly yesterday, but today I am able to console log the query.id without any issues. However, my cooki ...

Will synchronous programming on an Express server prevent other users from accessing the page simultaneously?

Currently working on a simple one-page web app that depends on loading weather data from a file. To avoid multiple HTTP requests for each visitor, I have a separate script refreshing the data periodically. In this particular instance, I am using fs.readFi ...

I'm encountering some errors while trying to deploy on Vercel. Is there anyone who could lend a hand with the following issues I'm

Cloning repository github.com/gmcnally78/-Final-Data-Driven-FullStack-App2 (Branch: main, Commit: e1d0133) Clone process completed in: 643.936ms Analyzing source code... Installing build runtime... Build runtime installation time: 2.278s Checking for ...

Replace Material UI propTypes with new definitions

I am currently working with React, Typescript, and Material UI. To globally disable the ripple effect for the ListItem component, I am using createMuiTheme.props in the following manner: createMuiTheme({ props: { MuiListItem: { disableRipple: t ...

`Unable to update the checked prop in MUI switch component`

The value of RankPermission in the switchPermission function toggles from false to true, but for some reason, the MUI Switch component does not update in the browser. I haven't attempted any solutions yet and am unsure why it's not updating. I&ap ...

What is the correct way to set a function as the value for an object without using quotation marks?

I am facing a challenge of generating very large JavaScript files using Node.js. Each file contains a const variable that holds values tailored for the specific file, with these values only known at runtime. For example: 'use strict' const lib ...

Error message thrown when attempting to cast an object to an ObjectId within a Mongoose model schema reference array: "CastError: Unable to cast value '[object Object]'

I recently constructed a blog website using express.js and mongoosejs. An article on this site can belong to one or more categories. However, when attempting to create a new article, I encountered the following error: { [CastError: Cast to ObjectId failed ...

BookshelfJS: Establishing a One-to-One Relationship

Within my database, I am working with two tables - User and Address. The User table consists of the following two methods: shippingAddress: function() { var Address = require(appRoot + '/config/db').model('Address'); return thi ...