Sequelize model.sync() 抛出错误
Sequelize model.sync() is throwing an error
我正在尝试创建一个带有 sequelize 的模型并添加然后使用 sync({ force: true }) 如图所示 here 让 MySQL 创建 table 如果没有'存在。然而,它对我大喊大叫说我在 MySQL 查询中有错误(应该由 Sequelize 生成)。
这是型号:
// admin.model.js
const { Sequelize, DataTypes } = require('sequelize');
const sequelize = require('../db/connection');
const validator = require("validator")
const Admin = sequelize.define('Admin', {
email: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
validate(value) {
if (!validator.isEmail(value)) {
throw new Error('Invalid email');
}
},
},
password: {
type: DataTypes.STRING,
allowNull: false,
validate(value) {
if (!value.match(/\d/) || !value.match(/[a-zA-Z]/)) {
throw new Error('Password must contain at least one letter and one number');
}
},
private: true, // used by the toJSON plugin
},
firstName: {
type: DataTypes.STRING,
allowNull: false
},
lastName: {
type: DataTypes.STRING,
allowNull: false
},
phone: {
type: DataTypes.NUMBER
},
}, {
freezeTableName: true
}
)
module.exports = Admin;
这就是我正在尝试的功能 运行
// sync.js
const Admin = require("../models/admin.model")
const synchronizeTables = async () => {
try {
await Admin.sync({ force: true })
console.log("Admin Table synchronized")
} catch (error) {
console.error(error)
}
}
module.exports = synchronizeTables
然后我在 db 目录中有一个 index.js 文件,用于导出连接和同步:
// index.js
const db = require("./connection");
const sync = require("./sync");
module.exports = { db, sync };
然后,我将它们导入 app.js 和 运行 sync
// app.js
const { db, sync } = require('./src/db');
sync()
我在 运行 服务器时得到的错误:
Server is up and running on port 8000
Executing (default): SELECT 1+1 AS result
Executing (default): DROP TABLE IF EXISTS `Admin`;
Connection has been established successfully.
Executing (default): CREATE TABLE IF NOT EXISTS `Admin` (`id` INTEGER NOT NULL auto_increment , `email` VARCHAR(255) NOT NULL UNIQUE, `password` VARCHAR(255) NOT NULL, `firstName` VARCHAR(255) NOT NULL, `lastName` VARCHAR(255) NOT NULL, `phone` NUMBER, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB;
DatabaseError [SequelizeDatabaseError]: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'NUMBER, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KE' at line 1
at Query.formatError (/home/ikdem/work/upwork/saas/admin-side/node_modules/sequelize/lib/dialects/mysql/query.js:265:16)
at Query.run (/home/ikdem/work/upwork/saas/admin-side/node_modules/sequelize/lib/dialects/mysql/query.js:77:18)
at processTicksAndRejections (internal/process/task_queues.js:97:5) {
parent: Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'NUMBER, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KE' at line 1
at Packet.asError (/home/ikdem/work/upwork/saas/admin-side/node_modules/mysql2/lib/packets/packet.js:712:17)
at Query.execute (/home/ikdem/work/upwork/saas/admin-side/node_modules/mysql2/lib/commands/command.js:28:26)
at Connection.handlePacket (/home/ikdem/work/upwork/saas/admin-side/node_modules/mysql2/lib/connection.js:425:32)
at PacketParser.onPacket (/home/ikdem/work/upwork/saas/admin-side/node_modules/mysql2/lib/connection.js:75:12)
at PacketParser.executeStart (/home/ikdem/work/upwork/saas/admin-side/node_modules/mysql2/lib/packet_parser.js:75:16)
at Socket.<anonymous> (/home/ikdem/work/upwork/saas/admin-side/node_modules/mysql2/lib/connection.js:82:25)
at Socket.emit (events.js:315:20)
at addChunk (_stream_readable.js:295:12)
at readableAddChunk (_stream_readable.js:271:9)
at Socket.Readable.push (_stream_readable.js:212:10) {
code: 'ER_PARSE_ERROR',
errno: 1064,
sqlState: '42000',
sqlMessage: "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'NUMBER, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KE' at line 1",
sql: 'CREATE TABLE IF NOT EXISTS `Admin` (`id` INTEGER NOT NULL auto_increment , `email` VARCHAR(255) NOT NULL UNIQUE, `password` VARCHAR(255) NOT NULL, `firstName` VARCHAR(255) NOT NULL, `lastName` VARCHAR(255) NOT NULL, `phone` NUMBER, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB;',
parameters: undefined
},
因此,Sequelize 生成的 SQL 查询似乎有错误。可能是我没用对吧。请帮助:)
所以这里的问题是 phone 的数据类型。如您所见,DataType.NUMBER 并没有在查询中变为 INTEGER,而是保持为 NUMBER,而 SQL 中不存在。
所以,我不得不改变
phone: {
type: DataTypes.NUMBER
},
至
phone: {
type: DataTypes.INTEGER
},
此外,我使用 sequelize.sync() 一次同步所有表,而不是一个一个地同步模型。
我正在尝试创建一个带有 sequelize 的模型并添加然后使用 sync({ force: true }) 如图所示 here 让 MySQL 创建 table 如果没有'存在。然而,它对我大喊大叫说我在 MySQL 查询中有错误(应该由 Sequelize 生成)。 这是型号:
// admin.model.js
const { Sequelize, DataTypes } = require('sequelize');
const sequelize = require('../db/connection');
const validator = require("validator")
const Admin = sequelize.define('Admin', {
email: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
validate(value) {
if (!validator.isEmail(value)) {
throw new Error('Invalid email');
}
},
},
password: {
type: DataTypes.STRING,
allowNull: false,
validate(value) {
if (!value.match(/\d/) || !value.match(/[a-zA-Z]/)) {
throw new Error('Password must contain at least one letter and one number');
}
},
private: true, // used by the toJSON plugin
},
firstName: {
type: DataTypes.STRING,
allowNull: false
},
lastName: {
type: DataTypes.STRING,
allowNull: false
},
phone: {
type: DataTypes.NUMBER
},
}, {
freezeTableName: true
}
)
module.exports = Admin;
这就是我正在尝试的功能 运行
// sync.js
const Admin = require("../models/admin.model")
const synchronizeTables = async () => {
try {
await Admin.sync({ force: true })
console.log("Admin Table synchronized")
} catch (error) {
console.error(error)
}
}
module.exports = synchronizeTables
然后我在 db 目录中有一个 index.js 文件,用于导出连接和同步:
// index.js
const db = require("./connection");
const sync = require("./sync");
module.exports = { db, sync };
然后,我将它们导入 app.js 和 运行 sync
// app.js
const { db, sync } = require('./src/db');
sync()
我在 运行 服务器时得到的错误:
Server is up and running on port 8000
Executing (default): SELECT 1+1 AS result
Executing (default): DROP TABLE IF EXISTS `Admin`;
Connection has been established successfully.
Executing (default): CREATE TABLE IF NOT EXISTS `Admin` (`id` INTEGER NOT NULL auto_increment , `email` VARCHAR(255) NOT NULL UNIQUE, `password` VARCHAR(255) NOT NULL, `firstName` VARCHAR(255) NOT NULL, `lastName` VARCHAR(255) NOT NULL, `phone` NUMBER, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB;
DatabaseError [SequelizeDatabaseError]: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'NUMBER, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KE' at line 1
at Query.formatError (/home/ikdem/work/upwork/saas/admin-side/node_modules/sequelize/lib/dialects/mysql/query.js:265:16)
at Query.run (/home/ikdem/work/upwork/saas/admin-side/node_modules/sequelize/lib/dialects/mysql/query.js:77:18)
at processTicksAndRejections (internal/process/task_queues.js:97:5) {
parent: Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'NUMBER, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KE' at line 1
at Packet.asError (/home/ikdem/work/upwork/saas/admin-side/node_modules/mysql2/lib/packets/packet.js:712:17)
at Query.execute (/home/ikdem/work/upwork/saas/admin-side/node_modules/mysql2/lib/commands/command.js:28:26)
at Connection.handlePacket (/home/ikdem/work/upwork/saas/admin-side/node_modules/mysql2/lib/connection.js:425:32)
at PacketParser.onPacket (/home/ikdem/work/upwork/saas/admin-side/node_modules/mysql2/lib/connection.js:75:12)
at PacketParser.executeStart (/home/ikdem/work/upwork/saas/admin-side/node_modules/mysql2/lib/packet_parser.js:75:16)
at Socket.<anonymous> (/home/ikdem/work/upwork/saas/admin-side/node_modules/mysql2/lib/connection.js:82:25)
at Socket.emit (events.js:315:20)
at addChunk (_stream_readable.js:295:12)
at readableAddChunk (_stream_readable.js:271:9)
at Socket.Readable.push (_stream_readable.js:212:10) {
code: 'ER_PARSE_ERROR',
errno: 1064,
sqlState: '42000',
sqlMessage: "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'NUMBER, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KE' at line 1",
sql: 'CREATE TABLE IF NOT EXISTS `Admin` (`id` INTEGER NOT NULL auto_increment , `email` VARCHAR(255) NOT NULL UNIQUE, `password` VARCHAR(255) NOT NULL, `firstName` VARCHAR(255) NOT NULL, `lastName` VARCHAR(255) NOT NULL, `phone` NUMBER, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB;',
parameters: undefined
},
因此,Sequelize 生成的 SQL 查询似乎有错误。可能是我没用对吧。请帮助:)
所以这里的问题是 phone 的数据类型。如您所见,DataType.NUMBER 并没有在查询中变为 INTEGER,而是保持为 NUMBER,而 SQL 中不存在。 所以,我不得不改变
phone: {
type: DataTypes.NUMBER
},
至
phone: {
type: DataTypes.INTEGER
},
此外,我使用 sequelize.sync() 一次同步所有表,而不是一个一个地同步模型。