Cannot perform table inserts or creates with NestJS Sequelize functionality

I am currently in the process of setting up a small web server with a MySQL database. To achieve this, I am utilizing NestJs along with Sequelize. However, as I am still in the learning phase, I seem to be encountering an error:

Within my database, I have a single table defined as follows:

import {Column, Model, Table, DataType} from "sequelize-typescript";

@Table
export class ShiftActivity extends Model{
  @Column({
    allowNull: false,
    autoIncrement: true,
    primaryKey:true,
    type: DataType.UUIDV4,
    defaultValue: DataType.UUIDV4,
  })
  id: string;

  @Column
  externalId: number;

  @Column
  name: string;

  @Column
  acronym: string;

  @Column
  rgbCode: string;
}

Here is my service class implementation:

import {Injectable} from '@nestjs/common';
import {InjectModel} from '@nestjs/sequelize';
import {ShiftActivity} from './shift-activity.model';
import {Sequelize} from 'sequelize-typescript';

@Injectable()
export class ShiftsActivityService {
  constructor(
    @InjectModel(ShiftActivity)
    private shiftActivityTable: typeof ShiftActivity,
    private sequelize: Sequelize
  ) {
    this.shiftActivityTable.sync();
    this.init();
  }

  async init() {
    try {
      await this.shiftActivityTable.findAll().then(value => console.log(
        "findAll: ", value.toString()
      ));
      await this.create(
        "Sale",
        "S",
        "00ff00",
        null,
      ).then(value => console.log(
        "New activity '", value.name, "' created with ID: ", value.id.toString(),)
      );
 
    }catch(error){
      console.log(error);
    }
  }

      async create(
        name: string,
        acronym: string,
        rgbCode: string,
        externalId: string | null | undefined = null,
      ): Promise<ShiftActivity> {
        try {
          let newActivity;
          console.log("--\n  newActivity\n--");
          await this.sequelize.transaction(async t => {
            const transactionObject = {transaction: t};
            newActivity = await this.shiftActivityTable.create({
              externalId: -1,
              name: name,
              acronym: acronym,
              rgbCode: rgbCode,
            });
          });
          console.log("--\n  newActivity\n--");
          return newActivity;
        } catch (error) {
          console.log(error);
        }
      }
}

I am now attempting to insert some initial test data for building my API from that point onwards. The dependency injection and modules are functioning correctly, and the findAll() function works as expected. However, when calling the create() function, it results in an error that I am struggling to pinpoint. The output upon initializing via the constructor is as follows:

Executing (default): SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_NAME = 'Shifts' AND TABLE_SCHEMA = 'pepzeit_dev'
Executing (default): SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_NAME = 'ShiftActivities' AND TABLE_SCHEMA = 'pepzeit_dev'
Executing (default): SELECT `id`, `externalId`, `name`, `acronym`, `rgbCode`, `createdAt`, `updatedAt` FROM `ShiftActivities` AS `ShiftActivity`;
Executing (default): SHOW INDEX FROM `Shifts`
Executing (default): SHOW INDEX FROM `ShiftActivities`
findAll:
--
  newActivity
--
Executing (1cba25d7-8fb9-4fdc-a161-2133f5509985): START TRANSACTION;
Executing (default): INSERT INTO `ShiftActivities` (`id`,`externalId`,`name`,`acronym`,`rgbCode`,`createdAt`,`updatedAt`) VALUES (?,?,?,?,?,?,?);
Executing (1cba25d7-8fb9-4fdc-a161-2133f5509985): ROLLBACK;
Error:
    ...

The "activityTable" has been successfully injected, and as mentioned earlier, the findAll() method functions properly. Your assistance in resolving this issue would be greatly appreciated.

Answer №1

After some investigation, I discovered the issue: the "type: DataType.UUIDV4" was incorrect, causing sequelize to use a number instead.

@Table
export class ShiftActivity extends Model{
  @Column({
    allowNull: false,
    autoIncrement: true,
    primaryKey:true,
    type: DataType.UUID, //was type: DataType.UUIDV4,
    defaultValue: DataType.UUIDV4,
  })
  id: 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

Utilize TypeScript to access scope within a directive

Is there a way to access the controller's scope properties using my custom TypeScript directive? For example, in this snippet below, I am trying to retrieve and log scope.message: /// <reference path="typings/angularjs/angular.d.ts" ...

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 ...

Is it possible for me to listen to an AngularJS event using regular JavaScript, outside of the Angular framework?

Is it possible to listen to an event triggered in AngularJS using regular JS (outside of Angular)? I have a scenario where an event is being emitted using RxJS in Angular 2. Can I observe that event from pure JS? Here's some example pseudo code: imp ...

Is there a way to configure side={THREE.BackSide} using an external .glb file?

As a beginner in Threejs, I am trying to incorporate the use of side="THREE.BackSide" with an external model file named room.glb. My development environment consists of nextjs 13 (with typescript and app directory enabled) along with @react-three ...

An action in redux-toolkit has detected the presence of a non-serializable value

When I download a file, I store it in the payload of the action in the store as a File type. This file will then undergo verification in the saga. const form = new FormData(); if (privateKey && privateKey instanceof Blob) { const blob = new Blo ...

Adding dropdowns to divs in Angular applications

Currently, I am attempting to integrate a dropdown feature into a div element. The HTML code for the dropdown is generated dynamically within the code. When clicking on the dropdown button, it appears functional but unfortunately, the dropdown itself does ...

Angular Lifecycle Hook - Data loading initializes after the view initialization is complete

In my component, I have loaded a firestore document and converted it into a plain js object within the constructor. However, when trying to access the field values in the template, there is a slight delay in loading them. This results in an error being dis ...

TSX: Interface Definition for Nested Recursive Array of Objects

I'm having trouble making my typescript interface compatible with a react tsx component. I have an array of objects with possible sub items that I need to work with. Despite trying various interfaces, I always run into some kind of error. At the mome ...

Tips on implementing computed properties in Vue.js while using TypeScript

There is a significant amount of documentation on how to utilize Vue.js with JavaScript, but very little information on using TypeScript. The question arises: how do you create computed properties in a vue component when working with TypeScript? According ...

Guide on resolving the error "Type 'Emits' does not have any call signatures" in Vue 3 with the combination of script setup and TypeScript

I've come across some code that seems to be functioning properly, but my IDE is flagging it with the following warnings: TS2349: This expression is not callable. Type 'Emits' has no call signatures Below is the code snippet in question: ...

In Typescript, encountering a member of a union type with an incompatible signature while utilizing the find method on an array of

I need to verify if a specific value exists within an array of objects. The structure of my array is as follows: [ 0: { id: 'unique_obj_id', item: { id: 'unique_item_id', ... }, ... }, 1: {...} ] The objects in the ar ...

Is it possible for me to create a union type that connects parameters and responses in a cohesive manner

I'm interested in creating a custom type that functions can use to indicate to callers that an input parameter of a specific type corresponds to a certain output type. For instance, consider the following scenario: type ResponseMap = { requestPath: ...

Is it possible to obtain Literal types for object keys dynamically in typescript?

I am looking to extract the type of object keys. Below is a generic function for objects with keys as strings: type GenericInput = { [key:string]: {value:string,type:HTMLInputTypeAttribute,placeholder:string,min?:number,max?:number,required?:boolean, err ...

Upon updating my application from Angular 14 to 16, I encountered an overwhelming number of errors within the npm packages I had incorporated

After upgrading my angular application from v14 to v16, I encountered numerous peer dependencies issues, which led me to use the --force flag for the upgrade process. However, upon compiling, I am now faced with a multitude of errors as depicted in the scr ...

The magical form component in React using TypeScript with the powerful react-final-form

My goal is to develop a 3-step form using react-final-form with TypeScript in React.js. I found inspiration from codesandbox, but I am encountering an issue with the const static Page. I am struggling to convert it to TypeScript and honestly, I don't ...

How Typescript Omit/Pick erases Symbols in a unique way

Recently, I have delved into TypeScript and started working on developing some custom utilities for my personal projects. However, I encountered an issue with type mapping involving Pick/Omit/Exclude and other typing operations where fields with symbol key ...

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 ...

Exploring the world of typed props in Vue.js 3 using TypeScript

Currently, I am attempting to add type hints to my props within a Vue 3 component using the composition API. This is my approach: <script lang="ts"> import FlashInterface from '@/interfaces/FlashInterface'; import { ref } from &a ...

Angular ngFor Directive Failing to Display Menu Item Information on Right-Click Context Menu

Currently encountering an issue with implementing a right-click function in my context menu. The menu items are not appearing due to the second ngFor="let row" condition... however, I require the selected row object from a right click to pass in a JSON val ...

Guide for launching Electron on a local host server during development and for production builds

I have a project using Next.js + Electron + Typescript. I used the npx create-next-app --example with-electron-typescript command to generate the initial code. When I run npm run dev (which actually runs npm run build-electron && electron . ), the ...