执行Sequelize Seeder命令时出现'字段列表未知列'错误求助
解决Seeder执行时「Unknown column 'subscriptionPlanType' in 'field list'」错误
问题场景
为subscriptions表创建了迁移文件和Seeder文件,执行npx sequelize-cli db:seed:all命令时,抛出「Unknown column 'subscriptionPlanType' in 'field list'」错误,多次重建文件仍未解决。
迁移文件代码
'use strict'; /** @type {import('sequelize-cli').Migration} */ module.exports = { async up(queryInterface, Sequelize) { await queryInterface.createTable('subscriptions', { id: { allowNull: false, autoIncrement: true, primaryKey: true, type: Sequelize.INTEGER }, subscriptionPlanType: { type: Sequelize.STRING }, name: { type: Sequelize.STRING }, memberCount: { type: Sequelize.INTEGER }, amount: { type: Sequelize.FLOAT }, createdAt: { allowNull: false, type: Sequelize.DATE }, updatedAt: { allowNull: false, type: Sequelize.DATE } }); }, async down(queryInterface, Sequelize) { await queryInterface.dropTable('subscriptions'); } };
Seeder文件代码
"use strict"; /** @type {import('sequelize-cli').Migration} */ module.exports = { async up(queryInterface, Sequelize) { /** * Add seed commands here. * * Example: * await queryInterface.bulkInsert('People', [{ * name: 'John Doe', * isBetaMember: false * }], {}); */ return queryInterface.bulkInsert("Users", [ { subscriptionPlanType: "Monthly", name: "Tset1", memberCount: 15, amount: 65.99, createdAt: "Oct 17 2022 22:34:39", updatedAt: "Oct 17 2022 22:34:39", }, { subscriptionPlanType: "Yearly", name: "Test2", memberCount: 25, amount: 105.99, createdAt: "Oct 17 2022 22:34:39", updatedAt: "Oct 17 2022 22:34:39", }, ]); }, async down(queryInterface, Sequelize) { /** * Add commands to revert seed here. * * Example: * await queryInterface.bulkDelete('People', null, {}); */ }, };
错误原因
- 目标表名称错误:Seeder中
queryInterface.bulkInsert的目标表写为"Users",但实际要插入的是迁移文件创建的subscriptions表,Users表不存在subscriptionPlanType字段,因此触发报错。 - 次要问题:第一条数据的
name字段值为"Tset1",属于拼写错误。
修复方案
- 修改Seeder文件中
bulkInsert的目标表名称,将"Users"改为"subscriptions" - 可选:修正第一条数据的
name拼写错误为"Test1" - 补充
down方法中的删除逻辑,确保可以回滚种子数据
修正后的Seeder文件
"use strict"; /** @type {import('sequelize-cli').Migration} */ module.exports = { async up(queryInterface, Sequelize) { return queryInterface.bulkInsert("subscriptions", [ { subscriptionPlanType: "Monthly", name: "Test1", memberCount: 15, amount: 65.99, createdAt: "Oct 17 2022 22:34:39", updatedAt: "Oct 17 2022 22:34:39", }, { subscriptionPlanType: "Yearly", name: "Test2", memberCount: 25, amount: 105.99, createdAt: "Oct 17 2022 22:34:39", updatedAt: "Oct 17 2022 22:34:39", }, ]); }, async down(queryInterface, Sequelize) { await queryInterface.bulkDelete('subscriptions', null, {}); }, };
完成修改后重新执行命令:
npx sequelize-cli db:seed:all
内容的提问来源于stack exchange,提问作者Jayna Tanawala
相关产品推荐
相关产品推荐

