Sequelize is not giving the expected model even after utilizing `include: [{ model: this.buildModel, required: true }]`

I've hit a roadblock trying to solve this problem. Despite my belief that I've correctly handled the migration, model definition, and query, I'm unable to retrieve the build in my iteration.

Below are the models:

SequelizeBuildModel.ts

@Table({
  tableName: 'playablebuild',
  underscored: true,
})
export class SequelizeBuildModel extends Model<
  BuildModelAttributes,
  BuildModelCreationAttributes
> {
  public id!: number;

  ...

  @HasMany(() => SequelizeIterationModel)
  public iterations!: SequelizeIterationModel[];

  ...
}

SequelizeIterationModel.ts

import {
  BelongsTo,
  Column,
  ForeignKey,
  Model,
  Table,
} from 'sequelize-typescript';
import { SequelizeBuildModel } from './SequelizeBuildModel';
import { DataTypes, Optional } from 'sequelize';

export interface IterationModelAttributes {
  id: number;
  buildId: number;
  config: Record<string, unknown>;
}

export type IterationModelCreationAttributes = Optional<
  IterationModelAttributes,
  'id'
>;

@Table({
  tableName: 'iteration',
  underscored: true,
})
export class SequelizeIterationModel extends Model<
  IterationModelAttributes,
  IterationModelCreationAttributes
> {
  @BelongsTo(() => SequelizeBuildModel, { foreignKey: 'build_id' })
  public build!: SequelizeBuildModel;

  @ForeignKey(() => SequelizeBuildModel)
  @Column
  public buildId!: number;

  @Column({ type: DataTypes.JSONB })
  public config!: Record<string, unknown>;
}

Here is the query :

SequelizeIterationRepository

import { Iteration } from '../../../domain/entities/Iteration';
import { IterationRepository } from '../../../domain/ports/IterationRepository';
import {
  IterationModelCreationAttributes,
  SequelizeIterationModel,
} from '../models/SequelizeIterationModel';
import { InjectModel } from '@infra';
import { IterationMapper } from '../mappers/IterationMapper';
import { SequelizeBuildModel } from '../models/SequelizeBuildModel';

export class SequelizeIterationRepository implements IterationRepository {
  constructor(
    @InjectModel('SequelizeIterationModel')
    private readonly iterationModel: typeof SequelizeIterationModel,
    @InjectModel('SequelizeBuildModel')
    private readonly buildModel: typeof SequelizeBuildModel,
  ) {}

  public async save(iteration: Iteration): Promise<Iteration> {
    const parsedIteration = IterationMapper.toPersistence(iteration);
    return this.create(parsedIteration);
  }

  private async create(
    iteration: IterationModelCreationAttributes,
  ): Promise<Iteration> {
    const rawIteration = await this.iterationModel.create(iteration, {
      include: [{ model: this.buildModel, required: true }],
    });
    return IterationMapper.toDomain(rawIteration);
  }
}

I am specifically focusing on those lines where rawIteration remains empty regardless of what I do:

      include: [{ model: this.buildModel, required: true }],
    });

Upon inspecting the database, everything seems to be correct with the relationships and foreign keys.

Answer №1

After reviewing the Documentation, it seems that using a key of 'association' instead of 'model' is recommended. Additionally, you may find that the required: true condition is not required in this context.

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 complications when importing TypeScript declarations

I am facing a problem with importing declarations from an extended file (I am utilizing this typing). As per the example, I have included this code in my project: import * as SockJS from 'sockjs-client'; import BaseEvent = __SockJSClient.BaseEve ...

In Angular 5, a variable's value becomes undefined once it is subscribed to outside of its assigned

I keep encountering an undefined value when trying to assign the subscribed value to a variable in my code snippet below. service.ts getIpAddress() : Observable<any> { return this.http .get(this.Geo_Api) .map((response: ...

utilize the useRef hook to display the total number of characters within a text area

Introducing the following component: import React from 'react'; export interface TexareaProps extends React.TextareaHTMLAttributes<HTMLTextAreaElement> { maxLength?: number; id: string; } export const Textarea = React.forwardRef( ( ...

The object type in Typescript prohibits direct access to its properties

Currently, I am facing an issue while trying to define a variable with the Object type and initialize it with a property. When attempting to access that property, an error message 'Property ____ does not exist on type Object' is displayed. I have ...

Is there a way to retrieve the final value from an Observable?

Trying to retrieve the last value from an observable. Here is an example of the code: // RxJS v6+ import { lastValueFrom, Subject } from 'rxjs'; import { scan } from 'rxjs/operators'; async function main() { const subject = new Subje ...

Getter and Setter Implementation in Typescript without Using Classes

Check out these various SO questions discussing Typescript getters/setters: from 2015, Jan 2018, Sept 2018, and more. Now, the question arises - what is the best approach to define Typescript types for getters/setters in a plain JavaScript object without ...

Pre-requisites verification in TypeScript

I have a typescript class with various methods for checking variable types. How can I determine which method to use at the beginning of the doProcess() for processing the input? class MyClass { public static arr : any[] = []; // main method public stati ...

Is there a way to merge TypeScript code with C++ during compilation?

Currently, I have a project written entirely in C++. However, there is an additional file written in typescript because I couldn't find equivalent libraries in C++. This typescript file performs the following actions: It contains a typescript CLI cod ...

Running Swagger within an Angular 5 environment - a step-by-step guide!

How do I integrate Swagger into my UI? Here's what I tried: import * as SwaggerUI from 'swagger-ui'; @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.c ...

Apply a border to the div that has been selected

I have a tool for storing information and I am using *ngFor to display each instance in a line. Is there a way to add a border when clicking on a line? The border should only appear on the clicked line, disappearing from the previous one if another line i ...

Modify the JSON format for the API POST request

I need assistance with making an API POST call in Angular 8. The JSON object structure that needs to be sent should follow this format: -{}JSON -{}data -[]exp +{} 0 +{} 1 However, the data I am sending is currently in this format: - ...

Unable to locate the Chart object within the chartjs-plugin-labels.js file

Hello there, I am currently working on an Angular project where I want to incorporate a chart plugin. To achieve this, I executed the following commands: npm install angular2-chartjs npm install chartjs-plugin-labels Following that, I imported it into my ...

After compiling the code, a mysterious TypeScript error pops up out of nowhere, despite no errors being

Currently, I am delving into the world of TypeScript and below you can find the code that I have been working on: const addNumbers = (a: number, b: number) => { return a + b } Before compiling the file using the command -> tsc index.ts, the ...

What is the best way to troubleshoot a quasar typescript file type error?

Currently, I am delving into Quasar using TypeScript and encountering a type error while working on file uploads. Here is the snippet of my code where the type error arises specifically in the parameter of the form.append() method. The error message read ...

Setting up data in Firebase can be challenging due to its complex structure definition

https://i.stack.imgur.com/iclx7.png UPDATE: In my firebase structure, I have made edits to the users collection by adding a special list called ListaFavorite. This list will contain all the favorite items that users add during their session. The issue I a ...

Creating a return type in TypeScript for a React Higher Order Component that is compatible with a

Currently utilizing React Native paired with TypeScript. Developed a HOC that functions as a decorator to add a badge to components: import React, { Component, ComponentClass, ReactNode } from "react"; import { Badge, BadgeProps } from "../Badge"; functi ...

Is there a way to utilize an Event Emitter to invoke a function that produces a result, and pause until the answer is provided before continuing?

Looking for a way to emit an event from a child component that triggers a function in the parent component, but with a need to wait for a response before continuing. Child @Output() callParentFunction = new EventEmitter<any>(); ... this.callParen ...

Encountering a hiccup while trying to install Svelte, Skeleton, and Tail

Recently entering the world of Svelte and TypeScript, I have encountered some unexpected errors after installation. Despite following the same steps as before, I am puzzled by what is causing these issues. This is the process I followed: npm create svelte ...

Tips for creating Material UI elements using React and Typescript

I am looking to extend a component from the Material UI library by creating a custom component that encapsulates specific styles, such as for a modal wrapper. However, I feel that my current solution involving the props interface may not be ideal. Is the ...

Sequelize does not recognize the findOne property

I've been working on creating a model using Sequelize with a MySQL database. When trying to post to '/students/register', I keep encountering an error stating that findOne is not a function. I attempted requiring mysql without success and al ...