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