我将数据库设置为:
const Sequelize = require("sequelize");
const db = {};
const sequelize = new Sequelize("sequel", "root", "root", {
host: "localhost",
dialect: "mysql",
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
},
logging: false
});
db.Sequelize = Sequelize;
db.sequelize = sequelize;
module.exports = db;
我的用户模型如下:
const { Sequelize, sequelize } = require("../config/database");
const user = sequelize.define("users", {
id: {
type: Sequelize.UUIDV4,
allowNull: false,
primaryKey: true
},
email: {
type: Sequelize.STRING,
allowNull: false
},
password: {
type: Sequelize.STRING,
allowNull: false
},
createdAt: {
type: Sequelize.DATE,
defaultValue: Sequelize.NOW
}
});
user.sync();
module.exports = user;
当我运行服务器时,我的错误是:
Unhandled rejection SequelizeDatabaseError: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use
near 'UUIDV4 NOT NULL , `email` VARCHAR(255) NOT NULL, `password` VARCHAR(255) NOT NUL' at line 1
at Query.formatError (C:\Users\HP\Documents\sum\chiya\node_modules\sequelize\lib\dialects\mysql\query.js:239:16)
at Query.handler [as onResult] (C:\Users\HP\Documents\sum\chiya\node_modules\sequelize\lib\dialects\mysql\query.js:46:23)
at Query.execute (C:\Users\HP\Documents\sum\chiya\node_modules\mysql2\lib\commands\command.js:30:14)
at Connection.handlePacket (C:\Users\HP\Documents\sum\chiya\node_modules\mysql2\lib\connection.js:449:32)
at PacketParser.onPacket (C:\Users\HP\Documents\sum\chiya\node_modules\mysql2\lib\connection.js:72:12)
at PacketParser.executeStart (C:\Users\HP\Documents\sum\chiya\node_modules\mysql2\lib\packet_parser.js:75:16)
at Socket.<anonymous> (C:\Users\HP\Documents\sum\chiya\node_modules\mysql2\lib\connection.js:79:25)
at Socket.emit (events.js:200:13)
at addChunk (_stream_readable.js:290:12)
at readableAddChunk (_stream_readable.js:271:11)
at Socket.Readable.push (_stream_readable.js:226:10)
at TCP.onStreamRead (internal/stream_base_commons.js:166:17)
由于我是新手,因此我在做错什么导致该语法错误?
如果没有表,又要创建一件事。我对其进行了研究,但找不到任何明显的内容,因此我使用了user.sync()
。甚至正确吗?
答案 0 :(得分:2)
我认为错误是您用于表的ID列的数据类型。在documentation中,它表明您应按以下方式定义UUID列:
...
id: {
type: Sequelize.UUID,
defaultType: Sequelize.UUIDV4,
allowNull: false,
primaryKey: true
},
...
UUIDV4只是使用UUID v4标准生成的默认唯一标识符,不应用作数据类型。
如果没有表,又要创建一件事。我对其进行了研究,但找不到任何明显的内容,因此我使用了user.sync()。甚至正确吗?
文档报告here时,它是正确的。如果数据库中不存在该表,则使用sync方法创建该表。