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

Encountering a problem when trying to use event.target.value in an Angular TypeScript application

Here is the code from my app.component.html : <h1>Password Generator</h1> <div> <label>Length</label> </div> <input (input)="onChangeLength($event.target.value)"/> <div> <div> <input ...

The perplexing behavior of RxJS Observables with Mongo Cursors

Recently, I've been working on converting a mongo cursor into an observable using my own RxJS implementation. Despite finding numerous solutions online, I wanted to challenge myself by creating one from scratch. I would greatly appreciate it if someo ...

Experiencing difficulty creating query files for the apollo-graphql client

I'm currently attempting to learn from the Apollo GraphQL tutorial but I've hit a roadblock while trying to set up the Apollo Client. Upon executing npm run codegen, which resolves to apollo client:codegen --target typescript --watch, I encounter ...

Arranging elements within an outer array by the contents of their inner arrays

I need help organizing an array based on the alphabetical order of a specific value within the inner arrays. For example: I want to sort this array by the prefix "old," so old A, old B, etc. const array = [ { personName: "Vans", personTags: ["young", " ...

Error encountered in Next.js: TypeScript error with code ts(7031) - The binding element 'Component' is implicitly assigned the 'any' type

Converting my NextJS project to TypeScript presented a challenge for me. When working on my _app.tsx file, I came across a type error: 'pageProps' implicitly has an 'any' type. ts(7031). The error message likely resembled this image: ht ...

Customize your Joi message using the .or() method

I'm attempting to personalize a message for the .or() function in Joi, similar to this: https://i.stack.imgur.com/68dKx.png The default message from Joi is as follows: Validation Error: "value" must contain at least one of [optionOne, optionTwo] ...

What is preventing me from utilizing a union type in conjunction with redux connect?

Below is a brief example of the code I am working on: import { connect } from "react-redux"; interface ErrorProps { error: true; description: string; } interface NoErrorProps { error: false; } type TestProps = ErrorProps | NoErrorProps; ...

There seems to be a contradiction in my code - I am returning a Promise but TypeScript is throwing an error saying that the

I currently have a function that retrieves a bot's inventory on the Frontend fetchBotInventory() { this.socket.emit('fetch bot inv'); this.socket.on('bot inv', (botInventory) => { return new Promise((resolve, re ...

Exploring Next JS: Effectively altering SVG attributes and incorporating new elements

I have integrated SVGR to load an SVG as a component in my latest Next.js 13 application: import CvSvg from './../../public/image.svg' export default function Home() { return ( <div className="flex flex-col min-h-screen" ...

Is Typescript compatible with the AWS Amplify Express API?

I've been struggling to set up my Amplify API in TypeScript and then transpile it to JavaScript. I know it sounds like a simple process, but I could really use some guidance on how to do this effectively. So far, I haven't progressed beyond the ...

What causes Gun.js to generate duplicate messages within a ReactJs environment?

I need assistance with my React application where gun.js is implemented. The issue I am facing is that messages are being duplicated on every render and update. Can someone please review my code and help me figure out what's wrong? Here is the code s ...

There has been no answer provided. Could this be due to being utilized in an asynchronous function that was not returned as a promise?

I encountered the following error message: Error: No response has been set. Is this being used in an async call that was not returned as a promise to the intent handler? at DialogflowConversation.response (/user_code/node_modules/actions-on-google/dis ...

Encountering difficulties when attempting to upload a file to Google Cloud Platform using Multer in a Node.js

I am currently experimenting with uploading a single file using Multer and the "multipart/form-data" content type to a Google Cloud Storage bucket. For this task, I am utilizing "Multer.memoryStorage()" and "@google-cloud/storage" try { const docume ...

The module "angular2-multiselect-dropdown" is experiencing a metadata version mismatch error

Recently, I updated the node module angular2-multiselect-dropdown from version v3.2.1 to v4.0.0. However, when running the angular build command, I encountered an "ERROR in Metadata version mismatch for module". Just to provide some context, I am using yar ...

implement some level of control within the ngFor directive in Angular

For instance, let's say I have an ngfor loop: <ng-container *ngFor="let setting of settings | trackBy: trackById"> <button mat-button [matMenuTriggerFor]="menu">Menu</button> <mat-me ...

Sending the :id parameter to the Service component

In the early days of my Angular journey, I have a simple question. Currently, I am utilizing the WordPress REST API to showcase a list of posts from a specific category by using posts?categories={ID HERE}. However, I am facing an issue in passing the ID f ...

Unable to attach to 'leafletOptions' as it is unrecognized as a property of 'div'

It seems like I keep encountering this problem, which is often resolved by adjusting import statements. Right now, my imports look like this: import { LeafletModule } from 'node_modules/@asymmetrik/ngx-leaflet'; import * as L from 'leaflet& ...

Issue occurs where the system is unable to recognize a defined variable, despite it being clearly defined

I keep encountering an error message stating that my variable is not defined, even though I have clearly defined it just a few lines above where the error occurs. The reason behind this error is baffling to me, as I cannot identify any potential triggers ...

Creating sparse fieldset URL query parameters using JavaScript

Is there a way to send type-related parameters in a sparse fieldset format? I need help constructing the URL below: const page = { limit: 0, offset:10, type: { name: 's', age:'n' } } I attempted to convert the above ...

A Fresh Approach for Generating Unique UUIDs without Bitwise Operators

To generate UUIDs in TypeScript, I have implemented a method inspired by the solution provided on Stack Overflow. The code effectively converts JavaScript to TypeScript. generateUUID(): string { let date = new Date().getTime(); if (window.performa ...