Похожие чаты

Hey guys , i'm using sequilize with nestjs but i

keep getting an error when i try to build an instance of a model , can you point me on what i'm doing wrong ? thanks
app.module.ts```
@Module({
imports: [
SequelizeModule.forRoot({
dialect: 'postgres',
host: 'localhost',
port: 5432,
username: 'user',
password: 'password',
database: 'visita',
models: [ typeof Category],
}),
CategoriesModule,
], controllers: [AppController],
providers: [AppService],
})
export class AppModule {}

categories.module.ts
@Module({
imports:[SequelizeModule.forFeature([Category])],
controllers: [CategoriesController],
providers: [CategoriesService],
})
export class CategoriesModule {}
@Injectable()
export class CategoriesService {
constructor(
@InjectModel(Category)
private readonly categoryModel: typeof Category,
) {}
async create(createCategoryDto: CreateCategoryDto) {
return this.categoryModel.create(createCategoryDto);
}
```

the error i'm getting :
ERROR [ExceptionsHandler] Cannot read properties of undefined (reading 'length')

i found this page and they are mainly saying that it has to do with registering models but i don't know what's the problem with this line : models: [ typeof Category], from the app.module.ts file

13 ответов

7 просмотров

What if you make this change? return this.categoryModel.create([createCategoryDto]);

mohammad- Автор вопроса

Why are you passing typeof Category?

mohammad- Автор вопроса
Darvesh 🍀
Why are you passing typeof Category?

that's what they are doing in the github page i shared , if i don't put typeof it gives this error : Type 'typeof Category' is not assignable to type 'string | ModelCtor'. i generated my models using sequlize-auto btw

mohammad- Автор вопроса

Show Category model

mohammad- Автор вопроса
Darvesh 🍀
Show Category model

export class Category extends Model<CategoryAttributes, CategoryCreationAttributes> implements CategoryAttributes { id!: number; name!: string; parent_id?: number; // Category belongsTo Category via parent_id parent!: Category; getParent!: Sequelize.BelongsToGetAssociationMixin<Category>; setParent!: Sequelize.BelongsToSetAssociationMixin<Category, CategoryId>; createParent!: Sequelize.BelongsToCreateAssociationMixin<Category>; // Category hasMany Product via category_id products!: Product[]; getProducts!: Sequelize.HasManyGetAssociationsMixin<Product>; setProducts!: Sequelize.HasManySetAssociationsMixin<Product, ProductId>; addProduct!: Sequelize.HasManyAddAssociationMixin<Product, ProductId>; addProducts!: Sequelize.HasManyAddAssociationsMixin<Product, ProductId>; createProduct!: Sequelize.HasManyCreateAssociationMixin<Product>; removeProduct!: Sequelize.HasManyRemoveAssociationMixin<Product, ProductId>; removeProducts!: Sequelize.HasManyRemoveAssociationsMixin<Product, ProductId>; hasProduct!: Sequelize.HasManyHasAssociationMixin<Product, ProductId>; hasProducts!: Sequelize.HasManyHasAssociationsMixin<Product, ProductId>; countProducts!: Sequelize.HasManyCountAssociationsMixin; static initModel(sequelize: Sequelize.Sequelize): typeof Category { return sequelize.define('Category', { id: { autoIncrement: true, type: DataTypes.INTEGER, allowNull: false, primaryKey: true }, name: { type: DataTypes.STRING(10), allowNull: false, unique: "categories_name_key" }, parent_id: { type: DataTypes.INTEGER, allowNull: true, references: { model: 'categories', key: 'id' } } }, { tableName: 'categories', schema: 'public', timestamps: false, indexes: [ { name: "categories_name_key", unique: true, fields: [ { name: "name" }, ] }, { name: "categories_pkey", unique: true, fields: [ { name: "id" }, ] }, ] }) as typeof Category; } } the sql table definiation is as simple as 3 fields and a foreign key

mohammad
export class Category extends Model<CategoryAttrib...

Follow this https://docs.nestjs.com/techniques/database#sequelize-integration

mohammad- Автор вопроса
mohammad
i did , that's how i ended up here 😁

Check https://docs.nestjs.com/techniques/database#models

mohammad- Автор вопроса
Darvesh 🍀
Check https://docs.nestjs.com/techniques/database#...

that's if i'm using autoLoadModels , but i wanna auto generate my models from my database , this way i should write them by hand :(

Try TS ignoring this once

Похожие вопросы

Обсуждают сегодня

30500 за редактор? )
Владимир
47
any reference of this implementation?
BitBuddha
29
Ⓐrtto, [4/23/24 7:02 PM] Please explain more fully how it is not working exactly, and what are the steps you are taking, and what error messages come or what happens. Ⓐrtto, ...
Ezza Kezza
2
sounds like people have lost their kaspa on tradeogre... does this mean tradeogre not trustworthy?
Ezza Kezza
15
Страшнейшая правда про списки ЦБ. С первых дней жизни P2P сферы, молодые человеки, начитавшись законодательной базы и "внутренних" документов, решили, что им противостоит сер...
Foxcool
3
Недавно Google Project Zero нашёл багу в SQLite с помощью LLM, о чём достаточно было шумно в определённых интернетах, которые сопровождались рассказами, что скоро всех "ибешни...
Alex Sherbakov
5
So much speculation in the last week. So much volatility in price. This is because Hedera has a GC that isn't using the network it's governing. Why aren't people asking why a...
Summit Seeker R
9
Anyone else having this error when trying to make transactions?
Datzel
11
Question: How viable is it to use Anvil as the backend infrastructure for managing a TradFi portfolio, while integrating Flexa for instant liquidity and payment solutions? Cou...
Kevin
2
вы делали что-то подобное и как? может есть либы готовые? увидел картинку нокода, где всё линиями соединено и стало интересно попробовать то же в ddl на lua сделать. решил с ч...
Victor
8
Карта сайта