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

Sequelize关联报错:无法读取undefined的'STRING'属性,求协助

解决Sequelize关联时的"Cannot read properties of undefined (reading 'STRING')"错误

错误根源

你在关联代码里调用模型构造函数时,只传了sequelize参数,没传DataTypes参数。模型定义函数依赖第二个参数DataTypes来声明字段类型,缺失这个参数会导致DataTypes为undefined,进而触发读取STRING属性的报错。

另外,由于User的主键是自定义的email而非默认的id,建立关联时必须显式指定外键规则,否则Sequelize会自动生成默认的userId外键字段,不符合你用email作为外键的需求。

修正方案

1. 关联代码修改

const Section = require("./Section");
const User = require("./User");
const { DataTypes } = require('sequelize');

module.exports=(sequelize)=>{
    // 调用模型时必须传入sequelize和DataTypes两个参数
    const user = User(sequelize, DataTypes);
    const section = Section(sequelize, DataTypes);
    
    // 显式指定外键关联规则
    user.hasOne(section, {
        foreignKey: 'email', // Section表中的外键字段名
        sourceKey: 'email'   // User表中的源主键字段
    });

    sequelize.sync({alter:true}).then(()=>{
        // 同步成功后的逻辑
    }).catch((err)=>{
        console.log(err)
    })
};

2. 可选:Section模型显式定义外键(推荐)

虽然Sequelize会自动创建外键字段,但显式定义能让表结构更清晰,避免隐式规则带来的混淆:

module.exports=(sequelize,DataTypes)=>{
    const Section=sequelize.define("Section",{
        HeroSec:{
            type:DataTypes.BOOLEAN,
            defaultValue: true,
            allowNull:false,
            validate:{
                notEmpty:true
            },
        },
        // 显式声明外键字段
        email: {
            type: DataTypes.STRING,
            allowNull: false,
            references: {
                model: 'User',
                key: 'email'
            }
        }
    },
    {
        freezeTableName: true
    });
    return Section;
}

验证注意事项

  • 所有模型调用必须同时传入sequelize和DataTypes参数
  • 自定义主键的关联必须显式配置foreignKey和sourceKey
  • alter:true会自动调整表结构,生产环境建议谨慎使用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 04:41:01