Setting default values for the primary column in TypeORMTypeORM allows you

Encountering an issue while attempting to save an entity to the database in NestJs using TypeORM due to a primary column with a default value not being set.

Summary How can I successfully define default column values in TypeORM when the default property appears ineffective?

UPDATE 1: Realized that default operates at the database level, although utilizing @BeforeInsert() does not resolve the issue as expected.

UPDATE 2: Discovered that the @BeforeInsert() hook functions only if .save() is invoked using .save(new UserSession(userId)) rather than .save({ userId: userId }), necessitating the appropriate constructor in UserSession.

The Scenario

In my entity UserSession, take note of the sessionId field intended to possess a default value generated by

cryptoRandomString({ length: 128, type: 'alphanumeric' })
.

@Entity('user_session')
export class UserSession {
    
    @PrimaryColumn({ 
        name: 'session_id',
        default: () => cryptoRandomString({ length: 128, type: 'alphanumeric' })
    })
    sessionId: string
    
    @Column({ 
        name: 'user_id',
    })
    userId: string
   
}

I utilize the TypeORM repository's .save() method to store the object in the database as shown below:

@Injectable()
export class AuthService {
    constructor(
        @InjectRepository(UserSession)
        private readonly userSessionRepository: Repository<UserSession>
    ) {}

    async createNewSession(userId: string): Promise<void> {
        // Create new session
        const session = await this.userSessionRepository.save({
            userId: userId
        })

       // Unfortunately, encountering issues...
    }
}

The Issue

Anticipating TypeORM to assign a default value to sessionId if left unset manually, yet an error is thrown instead:

[Nest] 23088   - 04/06/2021, 23:18:44   [ExceptionsHandler] ER_NO_DEFAULT_FOR_FIELD: Field 'session_id' doesn't have a default value +4032ms
QueryFailedError: ER_NO_DEFAULT_FOR_FIELD: Field 'session_id' doesn't have a default value
    at new QueryFailedError (E:\SAC\projects\api-flexrent\node_modules\typeorm\error\QueryFailedError.js:12:28)
    ...

Confusion

After exploring various options without success and encountering the same error repeatedly:

@PrimaryColumn({ 
    name: 'session_id',
    default: cryptoRandomString({ length: 128, type: 'alphanumeric' })
})
sessionId: string

or

@PrimaryColumn({ 
    name: 'session_id',
    default: () => 'cryptoRandomString({ length: 128, type: "alphanumeric" })'
})
sessionId: string

or

@PrimaryColumn({ 
    name: 'session_id',
    default: 'cryptoRandomString({ length: 128, type: "alphanumeric" })'
})
sessionId: string

or

@PrimaryColumn({ 
    name: 'session_id',
    default: 'please work'
})
sessionId: string

or alternatively avoiding specifying default within @PrimaryColumn() and opting for @BeforeInsert(), which seems inactive when using .save():

@BeforeInsert()
beforeInsertAction(): void {
    this.sessionId = cryptoRandomString({ length: 128, type: 'alphanumeric' })
}

The lone successful approach involved employing a constructor in the UserSession class to set the sessionId:

constructor(
    userId: string
) {
    this.userId = userId
    this.sessionId = cryptoRandomString({ length: 128, type: 'alphanumeric' })
}

and invoking it via

const session = await this.userSessionRepository.save(new UserSession(userId))

Have I overlooked something critical? Is my methodology fundamentally flawed from the outset? Uncertainty prevails.

Answer №1

After much trial and error, I finally came up with a solution that effectively addresses the issue...

Here is how I redefined my entity class:

@Entity('user')
export class User {

  @PrimaryColumn({ 
    name: 'user_id',
    type: 'varchar',
    length: 32
  })
  userId: string = cryptoRandomString({ length: 32, type: 'alphanumeric' })

  @Column({ 
    name: 'session_id',
    type: 'varchar',
    length: 128
  })
  sessionId: string = cryptoRandomString({ length: 128, type: 'alphanumeric' })

  @Column({ 
    name: 'email',
    type: 'varchar',
    length: 128
  })
  email: string

}

Now, utilizing the repository's .create() method, I can easily generate a new user entity:

const user: User = this.userRepo.create({ email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bed6dbd2d2d190c9d1ccd2dafedbc6dfd3ced2db90ddd1d3">[email protected]</a>' })

This results in the following object being created:

user: {
  userId: 'ivWW8oMGD8oMh2FL0vM3Grrh2FL0M3Di'
  sessionId: 'vM3DiW8oMGrh2FL0vM3DiW8oMGrh2FL0vM3DiW8oMGrh2FL0vM3DiW8oMGrh2FL0...'
  email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="472f222b2b28693028352b2307223f262a372b226924282a">[email protected]</a>'
}

To persist this object, I simply use the .save() method:

await this.userRepo.save(user)

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

Using custom properties from the Material-UI theme object with custom props in Emotion styled components: a step-by-step guide

I have implemented a custom object called fTokens into the MUI theme using Module augmentation in TypeScript This is how my theme.d.ts file is structured declare module "@mui/material/styles" { interface FPalette { ... } interface FTokens ...

Effective ways to bypass SSL errors in Nuxt.js due to OSS upgrades

I recently updated the OSS versions in my nuxt project. Previously, I was using version "nuxt": "2.0.0" and now I have upgraded to the latest version "nuxt": "2.14.7". Everything seemed fine when I opened my web apps in the browser, but I received a warnin ...

I encountered an issue with my autocomplete feature in Angular TypeScript where it was returning a [object Object] value

Issue with autocomplete displaying [object Object] value in Angular TypeScript I'm having trouble pinpointing the exact problem HTML snippet <mat-form-field style="margin-right: 10px;"> <input #productName matInput placeholder="Product" ...

Is there a way to customize the text color highlight for a specific react component only?

I'm working with React and need to adjust the text highlight color. Initially, I tried this approach: Highlight.css ::selection { background:#fbc308; color: black } somecomponent.tsx import './highlight.css' However, this ende ...

Variations between objects?

There are two different methods for using objects in programming. I am curious to understand if the difference lies in the syntax or if there is more to it. Method 1 body(data) = { item1: data.val1; item2: data.val2; item3: data.val3; } Meth ...

TSX: Interface Definition for Nested Recursive Array of Objects

I'm having trouble making my typescript interface compatible with a react tsx component. I have an array of objects with possible sub items that I need to work with. Despite trying various interfaces, I always run into some kind of error. At the mome ...

Error message in NestJs jwt authentication global guards: Unable to access property 'secretOrKeyProvider' as it is undefined

When configuring my application, I have implemented global filters using the code snippet below. const server = await NestFactory.create(ApplicationModule); server.useGlobalGuards(new (AuthGuard('jwt'))); The structure of my ApplicationModule is ...

Best practice for incorporating the cq-prolyfill third-party JavaScript library into an Angular 5 application

I'm experiencing an issue with the cq-prolyfill library not functioning properly when included through a typescript import statement within an angular module. I have confirmed that it is included in my vendor bundle, but for some reason the initial se ...

Guide on importing CDN Vue into a vanilla Typescript file without using Vue CLI?

In the midst of a large project that is mostly developed, I find myself needing to integrate Vue.js for specific small sections of the application. To achieve this, I have opted to import Vue.js using a CDN version and a <script> </script> tag ...

Encapsulate the module function and modify its output

I am currently utilizing the node-i18n-iso-countries package and I need to customize the getNames function in order to accommodate a new country name that I wish to include. At the moment, I am achieving this by using an if-else statement like so: let cou ...

What is the process of expanding a npm module with TypeScript?

I am currently using joi in conjunction with @types/joi for TypeScript. Joi's extend method allows for the extension of joi by creating a new instance without altering the original joi library. I have successfully created an extended instance using th ...

NestJS Troubleshooting: Nest is unable to resolve dependencies required by the ChildService

My project has a class structure set up like this: Inside the libs/childmodule/src/child.module.ts, I have a ChildModule. It is mapped to @app in the taconfig.json file. In addition, there is a ParentModule where I am attempting to import the ChildModule ...

Utilizing Google Sheets as a secure, read-only database for Angular applications without the need to make the sheet accessible to the

Seeking a way to utilize Google Sheets document as a read-only database for my Angular application, I have attempted various methods. However, the challenge with all these approaches is that they necessitate public sharing of the Sheet (accessible to anyon ...

The property functions normally outside the promise, but is undefined when within the promise context

I am currently working on filtering an array based on another array of different objects but with the same key field. Although I have made some progress, I keep encountering errors that I am unable to resolve. @Component({ selector: 'equipment&ap ...

Guide to dynamically displaying a markdown file in Angular?

Struggling to create an Angular component that can display markdown files on a webpage using the ngx-markdown library. The official demo of the library showcases a list of files it needs through require, which are then rendered: In the demo's app.com ...

Framer Motion's "repeatType" property triggering a TypeError

Every time I try to add the repeatType property in my transition, I encounter an error related to the variants prop: index.d.ts(2779, 5): The expected type comes from property 'variants' which is declared here on type 'IntrinsicAttributes ...

Error: 'Target is not found' during React Joyride setup

I am attempting to utilize React Joyride on a webpage that includes a modal. The modal is supposed to appear during step 3, with step 4 displaying inside the modal. However, I am encountering an issue where I receive a warning message stating "Target not m ...

Having difficulties testing the Angular HTTP interceptor with Karma and Jasmine

Testing an http interceptor has been quite the challenge for me. Despite having my token logged in the console and ensuring that the request URL matches, I still can't figure out why it's not working with the interceptor in place. Interestingly, ...

The React Table is showing an error due to incompatible property types for 'accessor'

Currently experimenting with react-table in a create-react-app project (version ^7.0.25). Utilizing the example provided in their quick start documentation. However, encountered a type error between the accessor and data columns. Below is the snippet of co ...

A step-by-step guide on integrating the CSS file of react-datepicker into a Nestjs SSR application with AdminJS

Currently, I am integrating the react-datepicker component into my SSR project built with Nest.js and Admin.js. To ensure that the React components function properly and are styled correctly, I need to include the line 'import 'react-datepicker/d ...