When attempting to save my submission object data to the database, TypeORM unexpectedly alters the information

I am encountering an issue with inserting my data into a database using TypeORM

The problem at hand is as follows: What needs to be sent to the database includes the following data: Title, Description, Userid, idCategoryService, and createdBy. The ids and title cannot be null

Here is my route:

public async create(req: Request, res: Response): Promise<Response> {
    try {
        const idUser = req.context?.userId;
        const service = req.body;
        await serviceSchema.validateAsync(service, opts);

    const serviceRepository = getRepository(Service);
    const existsService = await serviceRepository.findOne({
        where: {
            title: service.title, serviceCategory: service.idServiceCategory, user: idUser
        }
    });

    if (existsService) return this.sendErrorResponse(res, { code: 409, message: ['Service already created'] });
    const newService: Service = Object.assign(new Service(), { ...service, idUser: idUser, createdBy: idUser });
    console.log(newService)
    await serviceRepository.save(newService);
    return res.status(201).send({
        code: 201,
        message: 'Success',
        data: [newService]
    })
} catch (error) {
    return this.sendCreateUpdateErrorResponse(res, error);
}

}

Upon creation of the object with Object assign function: Displayed in console.log()

Service {
  title: 'Test1',
  description: 'Test2',
  idServiceCategory: 'e704a4c4-b984-493f-877c-d5b6f4fdeb5b',
  idUser: '32ce26fa-bebe-4cdd-af40-f3e338ba2b5c',
  createdBy: '32ce26fa-bebe-4cdd-af40-f3e338ba2b5c'
}

However, observing what was passed in the TypeORM log:

query: INSERT INTO "ijob_api"."Service"("id", "createdAt", "updatedAt", "title", "description", "createdBy", "closed", "idUser", "idServiceCategory") VALUES ($1, $2, $3, $4, $5, $6, $7, DEFAULT, DEFAULT) RETURNING "createdAt", "updatedAt" -- PARAMETERS: ["d458357e-7120-4d78-b66b-5b2a410efe79","2021-08-30T14:43:25.944Z","2021-08-30T14:43:25.944Z","Test1","Test2","32ce26fa-bebe-4cdd-af40-f3e338ba2b5c",0]

My idUser remains as 0

This leads to a driver error in PostgreSQL

 driverError: error: null value in column "idUser" of relation "Service" violates not-null constraint
//code: 23502 -- postgres

Answer №1

I found a solution to my problem by identifying an issue in the following method:

const newService: Service = Object.assign(new Service(), { ...service, idUser: idUser, createdBy: idUser });

The mistake was passing the userid before the user, when it should have been the other way around.

For example:

const newService: Service = Object.assign(new Service(), { user: idUser, ...service, createdBy: idUser });

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

Problem with moving functions from one file to another file via export and import

I currently have the following file structure: ---utilities -----index.ts -----tools.ts allfunctions.ts Within the tools.ts file, I have defined several functions that I export using export const. One of them is the helloWorld function: export const hel ...

How can resolvers in GraphQL optimize data fetching based on necessity?

I am working with two unique GraphQL types: type Author { id: String! name: String! } type Book { id: String! author: Author! name: String! } Within my database structure, there exists a foreign key inside the books table: table authors (pseu ...

Compiling TypeScript files with an incorrect path when importing, appending "index" at the end of the @angular/material library

I'm currently working on creating a library to collect and distribute a series of Angular components across various projects, with a dependency on angular/material2. My objective is to eventually publish it on npm. However, I've encountered an i ...

Construct a new table by extracting information from a JSON-formatted column in another table

Currently, I am using a Postgres server and here is the structure of my table: The genres of each movie are stored in a column in the following JSON array format: [ {'id': 18, 'name': 'Drama'}, {'id': 36, 'nam ...

Displaying JSON data using FormControls in Angular 5

Upon receiving Json values from the server, I am encountering an issue while binding them to respective textboxes. The problem arises as the value in the textbox appears as [object object] <h1>{{title}}</h1> <h3>Catalog</h3> ...

Learn how to implement icons within Textfield components using Material-UI and TypeScript in React

I have successfully created a form with validation using TypeScript Material UI and Formik. Now, I am looking to enhance the visual appeal by adding a material UI Icon within the textfield area. Below is a snippet of my code: import React from 'reac ...

Unable to associate ngModel because it is not recognized as a valid property of the "Component"

Currently, I am in the process of creating a custom form component using Angular 4. I have included all necessary components for ngModel to function properly, but unfortunately, it is not working as expected. Below is an example of my child component: ex ...

How can we utilize Typescript to check if the intern 4 page has finished loading?

I've managed to set up a function in intern 4 using TypeScript that waits for the page to load. However, there are instances where it doesn't work and throws a TimeOutError even when I catch the error within the function. Can someone please take ...

Utilizing Functions in Next.js with TypeScript: A Guide to Reusability

It is considered a best practice to separate data fetching functions into a folder named services, but I'm having trouble implementing this in my Next.js project. The function works when placed inside the component where I want to render the data, but ...

Upon subscribing to an observable, the initial value is invariably null

Here is an example of the ProfileService I am currently using: export class ProfileService { private user: BehaviorSubject<User> = new BehaviorSubject<User>(null); constructor(private userService: UserService) { this.userService.getUs ...

Saving many-to-many relationships with entities that are already saved in TypeORM

As a beginner in Typeorm, I have been working on a web page with Angular + Typeorm for the past few weeks. Despite my efforts to resolve this issue by myself and researching previously asked questions here on Stackoverflow, I have unfortunately been unable ...

I'm having trouble with my Angular app's TypeScript script unable to locate the modules within the node_modules directory

I am using an Angular app and need to include a script in my package.json. The script is written in Typescript and can be found at src/scripts/generate-blog-metadata.ts. const { promisify } = require('util'); const { resolve, join } = require(& ...

Having trouble changing file names in a Next.js 13 project

I've been facing an issue ever since Next.Js 13 updated the `pages` folder to a new `app` folder. Whenever I try to rename the default "Pages.tsx" file to something like "Home.tsx" or "Information.tsx", it breaks and shows a 404 Page error. The first ...

Transforming various date formats into the en-US format of mm/dd/yyyy hh:mm:ss can be accomplished through JavaScript

When encountering a date format in en-GB or European style (mm.dd.yyyy), it should be converted to the en-US format (mm/dd/yyyy). If the date is not already in en-US format, then it needs to be converted accordingly. ...

Having trouble utilizing a custom array of objects in TypeScript and React?

After rendering a Functional Component that retrieves a list of objects, I successfully run a foreach loop with it. However, when I attempt to make http requests with each object to create a new array, something seems off. The formatting appears to be inco ...

Using the hook to implement the useContext function in React

I came across this definition export interface user{ email:string name:string last_name:string } export type UserType= { user: user; setUser:(user:user) => void; } const [user,setUser] = useState <user> ({ email ...

When employing multiple joins, COUNT may yield decimal values

After executing this particular query, I receive the desired results in a well-organized manner. SELECT referer_trackings.cookie_first_url AS url, sum(purchases.price) AS sales, count(purchases.id) AS volume FROM purchases JOIN referer_trackings ON ref ...

Dynamic Angular component loading with lazy loading

In my Angular 4.1.3 project, I am currently developing a mapping application that incorporates lazy-loading for various tool modules. At present, the tools are loaded within the map using a router-outlet. However, I now need to expand this functionality to ...

Can you share the appropriate tsconfig.json configuration for a service worker implementation?

Simply put: TypeScript's lib: ['DOM'] does not incorporate Service Worker types, despite @types/service_worker_api indicating otherwise. I have a functional TypeScript service worker. The only issue is that I need to use // @ts-nocheck at t ...

Experimenting with a VSCode extension that requires the act of launching a folder/workspace

Currently, I am developing a custom VSCode extension that considers the path of the file being opened within the workspace. To create a reproducible test scenario, I want to open the test folder itself in VSCode and then proceed to open the test file with ...