How can I update a nullable database field to NULL using TypeORM?

Answering this seemingly simple question has proven to be quite challenging.

In my backend application using Express and Typescript, I am working on implementing a password reset feature. The database I am using is Postgres with Typeorm for data manipulation. Within my database, I have an entity called User that consists of two columns:

@Column({
    unique: true,
    nullable: true,
})
resetPasswordToken!: string;

@Column({ nullable: true, type: 'timestamp with time zone' })
resetPasswordExpiresAt!: Date;

When a user requests a password reset token, both the resetPasswordToken and resetPasswordExpiresAt fields are populated. Upon receiving the token via email, the user can proceed to reset their password. After the password has been successfully reset, I intend to clear these fields by setting them to null:

user.resetPasswordToken = null;
user.resetPasswordExpiresAt = null;
user.save()

However, attempting to assign the value of null triggers errors in Typescript:

Type 'null' is not assignable to type 'string'.

and

Type 'null' is not assignable to type 'Date'.

To resolve these errors, I modified the entity column definitions to allow for null values like so:

resetPasswordToken!: string | null;
...
resetPasswordExpiresAt!: Date | null;

But upon launching my Express application, I encountered a new issue when Typeorm attempted to connect to the database:

Data type "Object" in "User.resetPasswordToken" is not supported by "postgres" database.

 

How can I successfully set these fields to null without encountering errors?

Answer №1

Following a peaceful night's sleep, I was able to successfully resolve the issue at hand.

In Typeorm, the data type of database fields is determined by the type assigned to variables in your typescript entities. For example, when I specified string as the type in typescript for my entity, Typeorm converted it into a varchar field in my postgres database.

@Column({
    unique: true,
    nullable: true,
})
resetPasswordToken!: string;

However, this approach led to an error in my project. While the code snippet above seemed correct, Typescript interpreted both data types as part of a single object, causing confusion for Typeorm.

resetPasswordToken!: string | null;

To address this issue, I had to explicitly define the database field type like so:

@Column({
    type: 'text',
    unique: true,
    nullable: true,
})
resetPasswordToken!: string;

Answer №2

The provided answer is somewhat inaccurate. The default typeorm conversion for a string type in a MySQL database is actually "varchar". Therefore, using type: "text" would result in the column being defined incorrectly. To ensure compatibility with the default behavior, it is recommended to use TypeScript types like so:

@Column({
    type: String,
    unique: true,
    nullable: true,
})
resetPasswordToken!: string | null;

Answer №3

@Field('text', {
    isUnique: true,
    canBeNull: true,
})
confirmationCode!: string;

Answer №4

In order to resolve the issue at hand, I needed to specifically define the data type for the database field as shown below:

{
   name: "tag_id",
   type: "varchar",
   isNullable: true
},

Answer №5

If you want to save a Date with a null value, simply use the nullable:true option in the @Column() decorator and save the object without assigning any value to the property.

@Column('text', {
    unique: true,
    nullable: true,
})
resetPasswordToken: string;

//user.resetPasswordToken = null

user.save()

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

Encountering net::ERR_CONNECTION_REFUSED error with Socket IO on AWS EC2 while using ELB

Currently, I am operating a React application with node/express on an AWS EC2 instance that is integrated with an Elastic Load Balancer. Interestingly, Socket io functions smoothly when directly accessing the EC2 instance. However, as soon as I try to acc ...

Endpoint callbacks from Express and Socket.io

Here’s the situation: I have a basic express/socket.io application with some python clients using python-socketio that need to be notified when a user visits my endpoint. Once a socket connection is established, I store the socket.id in an array so I ca ...

The Next JS project fails to compile when a hyperlink is sent to the Link component from an external source

I am encountering an issue with a Menu Item component that pulls its href and label from another component known as NavBar. The strange thing is that it works perfectly fine when running yarn dev, but fails to build. However, when I make a simple change to ...

Encountering compilation issues when transitioning from Angular 7 to Angular 8

Upon upgrading my project to Angular 8, an unexpected error occurs during the build process: ERROR in HostResourceLoader: loader(C:/myapp/cli/src/app/pages/user-home/user-home.component.html) returned a Promise i 「wdm」: Failed to compile. Ho ...

What steps can be taken to retrieve error.data from RTK Query while utilizing typescript?

When I log error to the console, this is what I see: { status: 401, data: "Invalid password" } If I attempt to log error.data, an error occurs: The "data" property does not exist in the "FetchBaseQueryError|SerializedErr ...

Concealing parameters within a URL in a Node.js POST request

When submitting a form to a node.js server using the jQuery post method, the parameters are showing up in the URL. The code in my app.js file looks like this: var express = require('express'), app = express(), serv ...

Can native MongoDB commands be utilized with Mongoose?

For the project I'm working on, I am utilizing mongodb as the database with node.js on the server and incorporating the mongoose package. I am curious if it is feasible to implement native mongodb commands within mongoose. ...

How can I access a global variable in a node/express application on both the client and server side?

Imagine having a variable, x, which is initialized in the request as req.x in an express middleware. To make this variable accessible to the client via the template, we use <%- window.x = req.x %>. Now, if we want to use this variable globally, it c ...

The dynamic duo of applications in expressjs

Currently, I am in the process of developing an application using express js that will cater to various clients such as web and mobile. I have made the decision not to use a single app for both client types due to concerns about added burden from certain ...

"Patience is key: Allowing the axios API call to finish in Node/Express

I'm struggling with this code because I have little experience working with API calls like this one. The problem arises in a live environment where Node.js does not wait for the axios call to finish before rendering the page. Surprisingly, everything ...

Verify the API request with the database at a row level

Imagine a scenario where there is a database table dedicated to storing user orders. Order.id Product User 1 Product1 User1 2 Product2 User1 3 Product2 User2 4 Product1 User3 5 Product2 User3 6 Product3 User3 In addition, there exists a ...

TypeScript Error: The Object prototype must be an Object or null, it cannot be undefined

Just recently, I delved into TypeScript and attempted to convert a JavaScript code to TypeScript while incorporating more object-oriented features. However, I encountered an issue when trying to execute it with cmd using the ns-node command. private usern ...

What are the best methods for managing file uploads on a node.js and express 3.0 server?

Here is an example of file uploads using Express: https://github.com/visionmedia/express/blob/master/examples/multipart/index.js Express automatically stores each uploaded file in the temp folder for future use. My main concern is: Is this method secure? ...

How can one effectively utilize TypeScript with native JavaScript methods and calls?

After a long break from TypeScript, I am struggling to override implementations or use native methods in the .ts file. The ones highlighted in red, excluding this, are causing errors. https://i.sstatic.net/WhcRM.png I'm not getting autocomplete sup ...

Develop a Yeoman generator that incorporates API calls

After successfully creating a Yeoman generator, I now have the task of adding two additional questions to it. I already have these questions in place async prompting() { const prompts = [ { name: "appName", message: "Proje ...

Minimize overlap across both projects

One scenario is having two projects that utilize a lot of the same components. How can we minimize redundancy between them? Is there a way to make them shareable? Perhaps leveraging webpack could be the solution? ...

Unleashing the full potential of Angular 7: How a personalized class decorator can

My dilemma lies in the fact that I have a decorator which, when applied on ngOnInit, initiates a console.log. log.decorator.ts export function Log(): ClassDecorator { // The Decorator Factory return (target: Function) => { const ngOn ...

Implementing passport jwt authentication and merging the req object with a key named 'user'

Is there a consistent behavior in authentication by passport-jwt that adds an object named "user" to the req object? And where does this specific name "user" originate from? app.post('/profile', passport.authenticate('jwt', { sess ...

Delivering information to the user interface in Node Express

For some reason, I've repeated this process multiple times successfully, but now it's just not working. This code snippet shows how my router is set up: router.get('/', function(req, res, next) { Account.findOne( { _id: re ...

Deciphering JSON data in an Express.js application

In a Node.js/Express.js application, an API call is made to another server which responds with JSON data. However, the received JSON response is not being properly parsed into new variables. What specific modifications should be applied to the code below i ...