NestJS: Having unique nullable email addresses breaches either the not-null constraint or the unique constraint

I need to include an email field in my User class that can be both nullable and unique. Here is the code I currently have:

user.entity.ts:

export class User
{
    @Column({ name: 'email', nullable: true })
    @Index('users_email_idx', { unique: true })
    email!: string;
...

user-create.dto.ts:

export class UserCreateDto implements UserInputInterface {

    @IsEmail()
    @IsOptional()
    @MaxLength(255)
    email?: string;

...

When I make a creation request with "email: null", I receive a 500 error message stating "ERROR [ExceptionsHandler] null value in column "email" of relation "users" violates not-null constraint". On the other hand, if I try to send an existing email, I get another 500 error: ERROR [ExceptionsHandler] duplicate key value violates unique constraint "users_email_idx". What am I doing wrong?

Answer №1

Make sure to indicate in the column entity that this particular column can be nullable:

 @Column({ nullable: true })
 @Index('users_email_idx', { unique: true })
 email!: string;

Answer №2

To prevent errors in your DTO class validator, ensure it can accept null values from the user side. You can achieve this by incorporating the @IsOptional() decorator from a library such as class-validator. Update your @IsEmail() decorator to allow for null values like so -

 @IsEmail({}, { nullable: true })
 @MaxLength(255)
 email?: string;

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 Angular 5+ to fetch information from an ASP.NET Core Web API

Having trouble retrieving data from an ASP.NET Core 2.0 Web API with Angular 5+. The steps taken so far are as follows: An ASP.NET Core 2.0 Web API was created and deployed on a server. Data can be successfully retrieved using Postman or Swagger. Using ...

Managing File Validation with Yup and React Hook Form

Currently, I'm working on a form that includes an input field of type file. My goal is to make this particular field required. const { register, handleSubmit } = useForm({ defaultValues, resolver: yupResolver(schema), }); <form onSubmit={handl ...

NGXS Alert: Unable to resolve parameters for TranslationEditorState: (?)

I'm currently implementing NGXS for state management within my Angular 9 application. I've encountered a specific issue where any attempt at dependency injection in one of the state classes results in an error message stating "Error: Can't r ...

What is the process for determining the types of arguments for multiple functions in TypeScript?

const foo = (a: string, b: string) => { console.log('foo', a, b); }; const bar = (a: number, b: number) => { console.log('bar', a, b); }; const multiFactory = <M extends typeof foo | typeof bar>(method: M) => (. ...

Comparing Input and Output Event Binding

Can you provide reasons why using @Output for events is more advantageous than passing an @Input function in Angular 2+? Utilizing @Input: Parent Template: <my-component [customEventFunction]=myFunction></my-component> Inside parent-compone ...

What is the best way to create a type guard for a path containing a dynamic field

In certain scenarios, my field can potentially contain both a schema and an object where this schema is defined by key. How can a guard effectively tackle this issue? Below is an example of the code: import * as z from 'zod'; import type { ZodTy ...

Adding or removing form fields dynamically in Angular2

I have been attempting to dynamically append fields to the choices array upon clicking addNewChoice, but I have not been successful thus far. <form class="form-inline"> <fieldset *ngFor="let choice of choices"> <div class="form ...

Efficiently identify method calls and effectively control spans

I am in the process of integrating tracing into my nodejs application to automatically create spans and trace method invocations at runtime with minimal code changes. Currently, I am using opentelemetry for instrumentation. While implementing manual instr ...

react Concealing the Card upon clicking a different location

Utilizing a combination of React and TypeScript, this component allows for the card to be toggled between shown and hidden states upon clicking on the specified div tag. However, there is a need to ensure that the card is hidden even if another area outs ...

The unique Angular type cannot be assigned to the NgIterable type

As a newcomer to Angular, I was introduced to types and interfaces today. Excited to apply my new knowledge, I decided to enhance my code by utilizing a custom interface instead of a direct type declaration: @Input() imageWidgets: ImageWidget; Here is the ...

What is the best way to implement component lazy loading in Preact?

My objective is to create two bundles during the build process, one for the index.tsx file and another for the lazy.tsx file. I am confident that there are one or two options that I am overlooking. Check out the example project on GitHub - example project ...

Solving commitments through a series of actions

Can someone please explain why when resolving promises in a loop, accessing the loop variable is necessary for it to work correctly? Here's an example where logging occurs 5 times: for (let i = 0; i < 5; i++) { this.getData() .then(() ...

I am facing issues with Firebase functions where the parameters received from Express.js routes are

I am encountering an issue while trying to use firebase functions to host my expressjs webapp. For some reason, all get parameters appear to be undefined. Can anyone help me figure out what the problem might be? import functions= require("firebase-fun ...

Step-by-step guide on leveraging TypeScript types called "p-waterfall"

Utilizing p-waterfall has led me to seek guidance on how to implement the TypeScript types it offers. You can find the relevant types here. declare namespace pWaterfall { type Task<ValueType, ReturnType> = ( previousValue: ValueType ) => R ...

Error: The argument provided is of type 'unknown', which cannot be assigned to a parameter of type 'string'. This issue arose when attempting to utilize JSON.parse in a TypeScript implementation

I'm currently converting this code from Node.js to TypeScript and encountering the following issue const Path:string = "../PathtoJson.json"; export class ClassName { name:string; constructor(name:string) { this.name = name; } ...

Access the Angular application directly from the email

Our infrastructure consists of a .NET back-end, an Angular 5 application, and a nginx server. Upon registering your account in the application, you will receive an email with a verification link structured as follows: [root]/register/verify?userId=blabla& ...

Converting a TypeScript object into a JSON string

When working with TypeScript, I am facing a challenge while trying to initialize an object that requires a JSON string for the "options" parameter. Specifically, it pertains to the object mentioned here. It is crucial that the options parameter be in JSON ...

Ways to input a return value that may be an array depending on the input

I'm struggling to properly type the return value in TypeScript to clear an error. function simplifiedFn( ids: string | string[], ): typeof ids extends string[] ? number[] : number { const idsIsArray = Array.isArray(ids); const idsProvided = idsI ...

What steps should I take to fix the error "property scrollIntoView of null cannot be read"?

I start a new project using Angular .html file: <a (click)="go()">toto</a> <div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam iaculis ex porttitor semper iaculis. Nam dapibus erat interdum, scelerisque magna et, finibus ...

Struggling to make Cypress react unit testing run smoothly in a ReactBoilerplate repository

I have been struggling for the past 5 hours, trying to figure out how to make everything work. I even recreated a project's structure and dependencies and turned it into a public repository in hopes of receiving some assistance. It seems like there mi ...