When using Sequelize, you may notice that extra spaces are automatically added at the end of the DataTypes.CHAR data type

Here is an example of how I structure my Store.ts file:

import {DataTypes, Model, ModelAttributes} from "sequelize";

export default class Store extends Model {
  declare id: number
  declare name: string
  declare phone: string
}

export const StoreFields: ModelAttributes = {
  id: {
    type: DataTypes.INTEGER,
    autoIncrement: true,
    primaryKey: true,
  },
  name: {
    type: DataTypes.CHAR,
    allowNull: false,
  },
  phone: {
    type: DataTypes.CHAR,
  }
}

In a similar fashion, here is my Item.ts file setup:

import {DataTypes, Model, ModelAttributes} from "sequelize";

export default class Item extends Model {
  declare id: number
  declare name: string
  declare price: number
}

export const ItemFields: ModelAttributes = {
  id: {
    type: DataTypes.INTEGER,
    autoIncrement: true,
    primaryKey: true,
  },
  name: {
    type: DataTypes.CHAR,
    allowNull: false,
  },
  price: {
    type: DataTypes.INTEGER,
    allowNull: false,
  },
  storeid: {
    type: DataTypes.INTEGER,
    allowNull: false,
    references: {
      model: 'Store',
      key: 'id',
    },
    onDelete: 'CASCADE'
  }
}

To initialize these models, I use the following approach:

import {DataTypes, Model, ModelAttributes, ModelStatic, Sequelize} from "sequelize";
import Item, {ItemFields} from "./models/Item.js";
import Store, {StoreFields} from "./models/Store.js";

export const sequelize = new Sequelize(process.env.PGURL, {dialect: "postgres"});

void Item.init(ItemFields, {sequelize, timestamps: false, tableName: 'item', modelName: 'item'}).sync()
void Store.init(StoreFields, {sequelize, timestamps: false, tableName: 'store', modelName: 'store'}).sync()

Store.hasMany(Item, {
  foreignKey: "storeid",
})
Item.belongsTo(Store, {
  foreignKey: "storeid",
})

The issue arises when I run

Store.create({name: "test", phone: "testphone"})
as the model ends up with extra spaces at the end.

Please see the image link below for reference:

It's worth noting that there may be missing quotes in response.data.rows

Answer №1

Next time, I'll remember to use VARCHAR (DataTypes.STRING) instead of CHAR. CHAR adds spaces to meet the fixed length of 32767 characters.

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

Angular - A simple way to conceal a specific row in a mat-table using Angular

I am looking to dynamically hide or show a specific column in a table by clicking on a button. The goal is to hide or delete the weight column when the "hide weight" button is clicked, and then show the weight column when the "show weight" button is clicke ...

Tips for sending back a response after a request (post | get) is made:

In the service, there is a variable that verifies if the user is authorized: get IsAuthorized():any{ return this.apiService.SendComand("GetFirstKassir"); } The SendCommand method is used to send requests (either as a post or get request): ApiServi ...

Is there an alternative method to invoke the function aside from setTimeOut()?

if(i==1){ this.resetScreens(); this.editJobScreen1 = true; if(this.selectedLocations.length > 0){ this.locationService.getLocationByInput({ maxResultCount:16, skipCount: 0 }).subscribe((ele)=>{ ...

Mastering the art of duplicating an array of objects in TypeScript

I attempted the following strategy: this.strategies = []; this.strategiesCopy = [...this.strategies]; Unfortunately, it appears this method is not effective as it results in duplicates. ...

Angular - Unable to access property '$invalid' because it is null

Working on my login page with angular and typescript. Clicking the submit button should trigger the login function in the controller, but if the form is invalid, it should just return. New to typescript, I keep running into an error when trying to add an ...

What steps are necessary to integrate barrel file imports with my Angular 2 application?

Following the Angular 2 style guideline 04-10 Create and Import Barrels can be challenging, as it may lead to unexpected file loading issues. When running my app, I noticed that Angular attempts to load a non-existent file named "my-component-name-here.js" ...

The error message "Property 'value' is not present on type 'EventTarget & HTMLSelectElement'" indicates that the 'value' property is not recognized on the Event

Here is the code snippet that I am working with: interface IHandleSelection { (value: string): any | void; } interface IPipeChangeEventValueToFunction { (handler: IHandleSelection): (event: React.ChangeEvent<HTMLSelectElement>) => void; ...

Error message being thrown by Sequelize: "Value must be unique"

I'm currently working with Sequelize and a MySQL database, setting up a many-to-many relationship using a CostumerDriverTransaction model as a through table. However, I encountered an error when trying to create a row in this table which says "m ...

acquiring the main class instance within a function without relying on an arrow function

Within my Angular project, I have integrated a datatable with row grouping and row callbacks. Datatable Options openPositionDatatableOptions = { sDom: 'rt<"bottom"p>', ajax: (data, callback, settings) => { this.service.ge ...

Tips for passing a query parameter in a POST request using React.js

I am new to working with ReactJS and I have a question about passing boolean values in the URL as query parameters. Specifically, how can I include a boolean value like in a POST API call? The endpoint for the post call is API_SAMPLE: "/sample", Here is ...

Sending information from the parent component to the child Bootstrap Modal in Angular 6

As a newcomer to Angular 6, I am facing challenges with passing data between components. I am trying to launch a child component bootstrap modal from the parent modal and need to pass a string parameter to the child modal component. Additionally, I want t ...

Conditional types can be used as type guards

I have this simplified code snippet: export type CustomType<T> = T extends Array<unknown> ? {data: T} : T; function checkAndCast<T extends Array<unknown>>(value: CustomType<T>): value is {data: T} { return "data" ...

The SDK directory for TypeScript 1.3 in Visual Studio 2013 does not include the necessary tsc.exe file

Exciting news! Typescript v1.3 has been officially announced today. To fully utilize this update, I quickly installed the power tools update for VS2013. Upon completion of the installation, my Visual Studio environment now recognizes the "protected" keywo ...

Tips for creating ternary operator logic that account for numerous conditions and optional parameters:

Trying to create a logic for my validator functions that involves using objects as errorMaps for input validation. In the code snippet provided, args.drugName is an optional field. If the user provides text, we want to ensure it is greater than 3 letters; ...

Angular: Converting JSON responses from HttpClient requests into class instances

I am facing an issue with the following code: public fetchResults(searchTerm: string): Observable<Array<SearchResult>> { let params = new HttpParams().set('searchTerm', searchTerm); return this.http .get<Array< ...

"React with Typescript - a powerful combination for

I'm facing an issue trying to create a simple list of items in my code. Adding the items manually works, but when I try to map through them it doesn't work. Apologies for any language mistakes. import './App.css' const App = () => { ...

Trigger parent Component property change from Child Component in Angular2 (akin to $emit in AngularJS)

As I delve into teaching myself Angular2, I've encountered a practical issue that would have been easy to solve with AngularJS. Currently, I'm scouring examples to find a solution with Angular2. Within my top-level component named App, there&apos ...

Develop a wrapper for a function with multiple variations in TypeScript

Encountering an issue with the code below while attempting to create a proxy for a function with multiple overloads: // The target function function original (a: number): boolean; function original (a: string): boolean; function original (a: boolean): bool ...

Is there a way to customize the hover style of Material UI Select or Menu MenuItem using the theme?

The theme I designed import { createMuiTheme } from 'material-ui/styles'; export const MyTheme = createMuiTheme({ palette: { primary: { light: '#757ce8', main: '#3f50 ...

Tips for building an interface in TypeScript with a restricted range of indices

I'm working on a function that accepts parameters of type Record<string, string>. How can I define a type with a limited set of indexes without triggering a TypeScript compiler error? Is there a way to create an interface with only specific ind ...