Sequelize model.sync() 抛出错误

Posted

技术标签:

【中文标题】Sequelize model.sync() 抛出错误【英文标题】:Sequelize model.sync() is throwing an error 【发布时间】:2021-07-18 04:03:43 【问题描述】:

我正在尝试使用 sequelize 创建一个模型,然后添加然后使用 sync( force: true ) 如 here 所示,如果不存在则让 mysql 创建表。然而,它对我大喊大叫,说我在 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 并运行同步

// 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 查询似乎有错误。也许我没有正确使用它。请帮忙:)

【问题讨论】:

这是一个非常好的注释。我没注意到。标签是自动生成的,我没有仔细看。感谢您的关注 【参考方案1】:

所以这里的问题在于手机的数据类型。如您所见,DataType.NUMBER 在查询中并未更改为 INTEGER,而是保持为 NUMBER,这在 SQL 中不存在。 所以,我不得不改变

phone: 
        type: DataTypes.NUMBER
    ,

phone: 
        type: DataTypes.INTEGER
    ,

另外,我使用 sequelize.sync() 一次同步所有表,而不是一个一个地同步模型。

【讨论】:

您也可以尝试使用迁移而不是强制同步

以上是关于Sequelize model.sync() 抛出错误的主要内容,如果未能解决你的问题,请参考以下文章

sequelize抛出错误方言需要在express js中显式定义

等待总是抛出 SyntaxError:等待仅在 sequelize 的异步函数中有效 [重复]

Sequelize NodeJS 服务器抛出“ERR_UNKNOWN_ENCODING”错误

Sequelize:TimeoutError:ResourceRequest 超时

Sequelize '方言需要从 v4.0.0 开始明确提供'

Sequelize findAll 不是函数