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

Sequelize迁移时报Cannot read properties of undefined (reading 'toString')解决

Sequelize迁移错误:Cannot read properties of undefined (reading 'toString') 解决记录

错误现象

执行Sequelize迁移任务时终端抛出如下错误信息:

Sequelize CLI [Node: 16.10.0, CLI: 6.2.0, ORM: 6.7.0]

Loaded configuration file "db\config.js".
Using environment "development".
== 20211021030720-create-customers: migrating =======

ERROR: Cannot read properties of undefined (reading 'toString')

关联模型代码

const { Model, DataTypes, Sequelize } = require('sequelize');

const { USER_TABLE } = require('./user.model');

const CUSTOMER_TABLE = 'customers';

const CustomerSchema = {
  costomerId: {
    allowNull: false,
    autoIncrement: true,
    primaryKey: true,
    type: DataTypes.INTEGER,
  },
  customerName: {
    allowNull: false,
    type: DataTypes.STRING,
  },
  customerLastname: {
    allowNull: false,
    type: DataTypes.STRING,
  },
  customerPhone: {
    allowNull: true,
    type: DataTypes.STRING,
  },
  createdAt: {
    allowNull: false,
    type: DataTypes.DATE,
    field: 'create_at',
    defaultValue: Sequelize.NOW,
  },
  userId: {
    field: 'user_id',
    allowNull: false,
    type: DataTypes.INTEGER,
    references: {
      model: USER_TABLE,
      key: 'userId'
    },
    onUpdate: 'CASCADE',
    onDelete: 'SET NULL'
  }
}

class Customer extends Model {
  static associate(models) {
    this.belongsTo(models.User, {as: 'user'});
  }

  static config(sequelize) {
    return {
      sequelize,
      tableName: CUSTOMER_TABLE,
      modelName: 'Customer',
      timestamps: false
    }
  }
}

module.exports = { CUSTOMER_TABLE, CustomerSchema, Customer };

排查思路

前期查阅相关资料,怀疑错误是DataTypes属性无效导致,多次核对模型字段定义未发现异常。

解决方案

问题根源为迁移文件方法调用错误:创建表的迁移逻辑错误使用了.addColumn方法,该方法仅适用于在已存在的表中新增字段,首次创建表需调用.createTable方法。
修正后的迁移up方法代码如下:

module.exports = {
  up: async (queryInterface) => {
    await queryInterface.createTable(CUSTOMER_TABLE, CustomerSchema);
  },

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 04:39:02