When calling EntityManager.save(), any fields that are not provided will be saved as null values

Currently, I am using

@nestjs/typeorm": "^8.0.2
in conjunction with Postgres and encountering an unusual issue that seems like unexpected behavior:

When attempting to save a partial entity, the fields I specify are saved correctly, but the resulting value includes additional fields with null values. This makes it challenging for me to rely on the returned object as it now contains incorrect data.

As an example (in a simplified form), let's consider a Project Entity:

class Project extends BaseEntity {
    @PrimaryGeneratedColumn()
    id: number;

    @Column({ length: 150 })
    name: string;

    @Column({ nullable: true })
    data?: string;
}

My goal is to update only the name field, so suppose I have this function:

async saveName(proj: {id: number, name: string}): Promise<Partial<IProject>> {
    ... [some code]...
   return await entityManager.save(Project,  proj);
}

Now, if the entry in the database is:

{id: 1, name: 'a', data: 'my data' }

and I call:

await saveName({id: 1, name: 'b'})

The resulting value will be:

{id: 1, name: 'b', data: NULL }

I would expect the result to be:

{id: 1, name: 'b'}

or:

{id: 1, name: 'b', data: 'my data' }
(less ideal, but at least accurate)

In this context, please understand:

  1. This scenario is crucial for the nature of my project.
  2. I cannot always anticipate the fields to update; I need to modify the received object directly.

To summarize, the returned value is flawed.
Could this be a bug?
Is there any workaround available?

Answer №1

When using the <code>EntityManager.save()
method, you will receive a partial model instance that includes the keys you updated as well as any defaults provided by the database (in this case, it's null because the data column is nullable). Unfortunately, this behavior is not thoroughly documented.

To address this issue, you can:

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

Calculate the frequency of events in one table depending on varying dates in another table

I am faced with a scenario where I have two tables. The first table contains user IDs along with their respective period start and end dates, which vary for each user. user_id | start | end ------------------------------------------ ...

Efficiently transferring input to a Typescript file

Is there a better way to capture user input in Angular and pass it to TypeScript? <form > <input #input type="text" [(ngModel)]="inputColor" (input)="sendInput(input.value)" /> </form> The current method involves creating a ...

What could be causing the interface to malfunction when defining a type that includes an enum as a property key?

When dealing with an enum and wanting to use its values as keys in objects, the type declaration looks like this: enum Bar { A, B } let dictionary: BarDictType = { [Bar.A]: "foo", [Bar.B]: "bar" } type BarDictType = { ...

The .ts document is not recognized as a TypeScript module

Check out this SystemJS + TypeScript plunk, which was created using the official Angular plunk template. An error is being thrown: (SystemJS) SyntaxError: Missing initializer in const declaration at eval () ... This error occurs when the .ts file is t ...

Is it feasible to stop closure from capturing external variables in TypeScript?

Imagine I have the following piece of Typescript code: const a = 456 const b = () => a Is there a way to make the Typescript compiler detect and flag an error or warning during compilation indicating that function b is accessing an external variable a ...

There seems to be an issue with transitioning the React.js page

I'm currently working on managing the page with react-hook, react-router-dom, and redux. The login functionality has been implemented, and I've written the code to redirect to the main page upon successful login. To achieve this, I utilized hi ...

A PostgreSQL SQL Query for Analyzing Error Data

On the column codemap, there is JSON data containing codes that need to be extracted (from removed, revised, or added) for different coding parameter categories such as cpt, drg, modifiers, secondaryDiagnosis, principalDiagnosis, secondaryProcedure, observ ...

In Angular, dynamically updating ApexCharts series daily for real-time data visualization

I am currently working with apexchart and struggling to figure out how to properly utilize the updateseries feature. I have attempted to directly input the values but facing difficulties. HTML <apx-chart [chart]="{ type: ...

Implementing type inference for response.locals in Express with TypeScript

I need to define types for my response.locals in order to add data to the request-response cycle. This is what I attempted: // ./types/express/index.d.ts declare global { declare namespace Express { interface Response { locals: { ...

Customizing Angular tooltips based on specific conditions

Is it possible to implement a conditional tool tip? For instance, I am looking to only display the tool tip if cellData[id].length is greater than 120 within a div element. #solution <div matTooltip="Info about the action" class="{{cssCe ...

Angular2 - leveraging root-relative imports

Having trouble with imports in angular2/typescript? Want to use paths relative to the project root like 'app/components/calendar', but currently stuck using something like this: //app/views/order/order-view.ts import {Calendar} from '../../ ...

What is the way to assign a variable to ngClass in Angular?

I'm currently working on creating modals that will display different content based on which button is clicked. Each button should trigger a unique modal to appear, each with its own specific content inside. When a button is clicked, the 'active&a ...

Incorrect Angular Routing Component OpeningI am experiencing an issue where

I am facing an issue with lazy loading a module, where it is not correctly displaying the desired component. Even though the route seems correct, it shows a different component instead. https://i.sstatic.net/v4oAB.png Despite specifying the path for "Pus ...

Importing TypeScript enums into a Vue or browser context can lead to errors or the need for additional dependencies

I'm encountering a problem when trying to import type definitions from a separate module in my Vue project. Below is the structure of the typedefs I am attempting to import: import { Server, createServer } from "net"; export namespace Testable { ...

VS Code failing to refresh TypeScript in Vue files

Currently, I'm using Vue with Vue Single File Components (SFC) and TypeScript in vscode. However, I've noticed that the types I create in a .d.ts file are not being applied or updated in my .vue files. It's only when I reload the window that ...

Guide on how to specify the return type for useMutation in the 'react-query' library

Here is the code snippet provided: const setFriendCode = (data: Params) => api({ data }) const [mutateSetFriendCode, state] = useMutation<Response, Params>( setFriendCode ) An issue arises with the type of parameters in the code. The compiler ...

Navigating the NestJS @Get() Decorator: A Comprehensive Guide

The code snippet above demonstrates the functionality of accessing two different functions using URLs like http://localhost:3000/vehicle/availableVehicles and http://localhost:3000/vehicle/1. Both functions work properly in this setup. @Controller(&apo ...

Converting <reference path/> directive to ESM import: A step-by-step guide

As I embark on developing a TypeScript application, I've reached the realization that I am not a fan of using the <reference path /> triple-slash directive. Instead, I prefer utilizing import 'something'. However, every time I attempt ...

What is the process for creating a map in which the value type is determined by the key type?

Is it feasible to formulate a Map<K, V> in a manner where the type of the value relies on the type of the key, without explicitly specifying the key's type upon initializing the map? For instance: abstract class BaseA { a() {} } class ConcreteA1 ...

Place an image at the top of the canvas at a specific location

Currently, I am in the process of reconstructing this specific website My approach involves working with React (similar to the aforementioned site) and utilizing the same cropper tool that they have implemented. For cropping, I am incorporating react-imag ...