You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Sequelize TypeScript初始化添加自定义User模型报错求助

在Sequelize中添加自定义User模型的问题及解决方法

问题场景

尝试在Sequelize中初始化自定义User模型时出现类型错误,代码如下:

import { User } from "./models/User";
import { Sequelize } from "sequelize";

private async connectToPostgreSQL() {
this.sequelize = new Sequelize({
  database: this.POSTGRES_DB,
  username: this.POSTGRES_USER,
  password: this.POSTGRES_PASSWORD,
  host: this.POSTGRES_HOST,
  port: this.POSTGRES_PORT,
  dialect: "postgres",
  models: [User]
});
}

报错信息

No overload matches this call.
Overload 1 of 4, '(options?: Options | undefined): Sequelize', gave the following error.
Argument of type '{ database: string; username: string; password: string; host: string; port: number; dialect: "postgres"; models: any[]; }' is not assignable to parameter of type 'Options'.
Object literal may only specify known properties, and 'models' does not exist in type 'Options'.
Overload 2 of 4, '(uri: string, options?: Options | undefined): Sequelize', gave the following error.
Argument of type '{ database: string; username: string; password: string; host: string; port: number; dialect: string; models: any[]; }' is not assignable to parameter of type 'string'.ts(2769)

使用版本

"sequelize": "^6.34.0",
"sequelize-typescript": "^2.1.5"

解决方法

报错核心原因是你导入的是原生sequelize包的Sequelize类,它的配置选项里没有models属性。而你使用了sequelize-typescript,需要使用该库扩展后的Sequelize类来支持模型的直接配置。

步骤1:修正Sequelize导入路径

将Sequelize的导入源改为sequelize-typescript:

import { User } from "./models/User";
// 从sequelize-typescript导入扩展后的Sequelize
import { Sequelize } from "sequelize-typescript";

步骤2:确保User模型正确使用装饰器

你的User模型需要用sequelize-typescript的装饰器定义,示例如下:

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

@Table({ tableName: 'users' })
export class User extends Model {
  @Column
  username: string;

  @Column
  password: string;
  // 其他业务字段...
}

步骤3:重新初始化Sequelize

此时初始化代码中的models配置就会被正确识别:

private async connectToPostgreSQL() {
  this.sequelize = new Sequelize({
    database: this.POSTGRES_DB,
    username: this.POSTGRES_USER,
    password: this.POSTGRES_PASSWORD,
    host: this.POSTGRES_HOST,
    port: this.POSTGRES_PORT,
    dialect: "postgres",
    models: [User] // 现在符合类型定义
  });

  // 可选:测试数据库连接
  try {
    await this.sequelize.authenticate();
    console.log('数据库连接成功');
  } catch (error) {
    console.error('数据库连接失败:', error);
  }
}

批量加载模型(可选)

如果有多个模型,也可以通过modelPaths指定模型目录来批量加载:

this.sequelize = new Sequelize({
  // 其他配置项...
  modelPaths: [__dirname + '/models'] // 模型文件所在目录
});

内容的提问来源于stack exchange,提问作者nomoredope

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 22:23:21