执行sequelize-cli db:migrate时出现Cannot read properties of undefined错误
解决Sequelize迁移错误:Cannot read properties of undefined (reading 'type')
运行sequelize-cli db:migrate初始化数据库迁移时,触发以下错误:
ERROR: Cannot read properties of undefined (reading 'type')
完整错误输出:
Sequelize CLI [Node: 19.6.1, CLI: 6.6.0, ORM: 6.28.1] Loaded configuration file "config\config.js". == 20230221223939-aluno: migrating ======= ERROR: Cannot read properties of undefined (reading 'type')
相关配置文件
config.js
module.exports = { dialect: 'postgres', host: 'localhost', username: 'postgres', password: '123456', database: 'projetoBiblioteca', define: { timestamps: true, }, };
迁移文件
'use strict'; module.exports = { up: async (queryInterface, Sequelize) => { await queryInterface.createTable('aluno', { matricula: { type: Sequelize.INTEGER, allowNull: false, primaryKey: true, autoIncrement: false, }, nome: { type: Sequelize.STRING, allowNull: false, }, curso: { type: Sequelize.STRING, allowNull: false, }, ano: { type: Sequelize.INTEGER, allowNull: false, }, createdAt: { type: Sequelize.DATA, }, updatedAt: { type: Sequelize.DATA, }, }); }, down: async (queryInterface, Sequelize) => { await queryInterface.dropTable('aluno'); } };
package.json
{ "name": "projetobiblioteca", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "express": "^4.18.2", "pg": "^8.9.0", "pg-hstore": "^2.3.4", "sequelize": "^6.28.1" }, "devDependencies": { "nodemon": "^2.0.20" } }
问题修复
核心原因
迁移文件中createdAt和updatedAt字段使用了不存在的Sequelize数据类型Sequelize.DATA,正确的时间类型应为Sequelize.DATE。无效类型导致Sequelize无法识别,进而抛出错误。
修复代码
修改迁移文件中时间字段的类型:
createdAt: { type: Sequelize.DATE, allowNull: false, // 可选,结合config中timestamps配置,建议添加保证字段非空 }, updatedAt: { type: Sequelize.DATE, allowNull: false, },
额外提示
由于config.js已开启timestamps: true,Sequelize会自动为表添加createdAt和updatedAt字段,无需手动定义。如果需要自定义这两个字段,确保类型正确即可。
另外,确认已安装sequelize-cli:
npm install --save-dev sequelize-cli
之后通过npx sequelize-cli db:migrate重新执行迁移。
内容的提问来源于stack exchange,提问作者Khiuta
相关产品推荐
相关产品推荐

