Knex迁移报错:Cannot read properties of undefined (reading 'createTable')
执行
npx knex migrate:latest时迁移失败,报错Cannot read properties of undefined (reading 'createTable') 报错日志
npx knex migrate:latest migration file "20230917031623_createUsers.js" failed migration failed with error: Cannot read properties of undefined (reading 'createTable') Cannot read properties of undefined (reading 'createTable') TypeError: Cannot read properties of undefined (reading 'createTable') at exports.up (C:\PROJECTS\ENVOLVIDOS_api\src\database\knex\migrations\20230917031623_createUsers.js:1:35) at C:\PROJECTS\ENVOLVIDOS_api\node_modules\knex\lib\migrations\migrate\Migrator.js:519:40 at process.processTicksAndRejections (node:internal/process/task_queues:95:5) at async Migrator._runBatch (C:\PROJECTS\ENVOLVIDOS_api\node_modules\knex\lib\migrations\migrate\Migrator.js:381:19)
相关配置文件
knexfile.js
const path = require("path"); module.exports = { client: 'mysql2', connection: { database : 'shopbarber', user: 'root', password: '' }, pool: { min: 2, max: 10 }, migrations: { directory: path.resolve(__dirname, "src", "database", "knex", "migrations") } }
数据库配置文件
const config = require("../../../knexfile"); const knex = require("knex")(config); knex.raw("SELECT VERSION()").then(() => { console.log('Connection to db succesful') }) module.exports = knex;
迁移文件(原错误版本)
exports.up = knex => knex.schemas.createTable("users", table => { table.increments("id"); table.string("name", 60).notNullable(); table.string("telephone", 11).notNullable(); table.string("email", 90).notNullable().unique(); table.text("password").notNullable() table.string("avatar", 120); table.timestamp("created_at").defaultTo(knex.fn.now()); table.timestamp("updated_at").defaultTo(knex.fn.now()); }) exports.down = knex => knex.schemas.dropTable("users");
解决方案
错误根源是迁移文件中误用了复数形式的knex.schemas,Knex官方API中操作数据库schema的正确属性是单数的knex.schema,复数形式不存在,导致调用时schemas为undefined,进而触发报错。
修改迁移文件,将所有knex.schemas替换为knex.schema即可:
exports.up = knex => knex.schema.createTable("users", table => { table.increments("id"); table.string("name", 60).notNullable(); table.string("telephone", 11).notNullable(); table.string("email", 90).notNullable().unique(); table.text("password").notNullable() table.string("avatar", 120); table.timestamp("created_at").defaultTo(knex.fn.now()); table.timestamp("updated_at").defaultTo(knex.fn.now()); }) exports.down = knex => knex.schema.dropTable("users");
修改后重新执行npx knex migrate:latest即可完成迁移。
内容的提问来源于stack exchange,提问作者Esdras
相关产品推荐
相关产品推荐

