运行 express.js 应用时的续集问题

squelize issues when running express.js app

我正在尝试 运行 一个带有 Express、Sequelize 和 MySQL 的简单应用程序 我收到此错误:

Executing (default): CREATE TABLE IF NOT EXISTS `tasks` (`id` INTEGER NOT NULL auto_increment , `title` VARCHAR(255) NOT NULL, `description` VARCHAR(255) NOT NULL, `status` NUMBER NOT NULL, `createdBy` NUMBER, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB;
err:  Error
    at Query.run (C:\Users\Kryolos.Hakeem\desktop\vodafone-tech-test\back-end-v2\node_modules\sequelize\lib\dialects\mysql\query.js:52:25)
    at C:\Users\Kryolos.Hakeem\desktop\vodafone-tech-test\back-end-v2\node_modules\sequelize\lib\sequelize.js:313:28
    at processTicksAndRejections (internal/process/task_queues.js:95:5)
    at async MySQLQueryInterface.createTable (C:\Users\Kryolos.Hakeem\desktop\vodafone-tech-test\back-end-v2\node_modules\sequelize\lib\dialects\abstract\query-interface.js:94:12)   
    at async Function.sync (C:\Users\Kryolos.Hakeem\desktop\vodafone-tech-test\back-end-v2\node_modules\sequelize\lib\model.js:939:5)
    at async Sequelize.sync (C:\Users\Kryolos.Hakeem\desktop\vodafone-tech-test\back-end-v2\node_modules\sequelize\lib\sequelize.js:377:9) {
  name: 'SequelizeDatabaseError',
  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 NOT NULL, `createdBy` NUMBER, `createdAt` DATETIME NOT NULL, `updatedAt` ' at line 1
      at Packet.asError (C:\Users\Kryolos.Hakeem\desktop\vodafone-tech-test\back-end-v2\node_modules\mysql2\lib\packets\packet.js:728:17)
      at Query.execute (C:\Users\Kryolos.Hakeem\desktop\vodafone-tech-test\back-end-v2\node_modules\mysql2\lib\commands\command.js:29:26)
      at Connection.handlePacket (C:\Users\Kryolos.Hakeem\desktop\vodafone-tech-test\back-end-v2\node_modules\mysql2\lib\connection.js:456:32)
      at PacketParser.onPacket (C:\Users\Kryolos.Hakeem\desktop\vodafone-tech-test\back-end-v2\node_modules\mysql2\lib\connection.js:85:12)
      at PacketParser.executeStart (C:\Users\Kryolos.Hakeem\desktop\vodafone-tech-test\back-end-v2\node_modules\mysql2\lib\packet_parser.js:75:16)
      at Socket.<anonymous> (C:\Users\Kryolos.Hakeem\desktop\vodafone-tech-test\back-end-v2\node_modules\mysql2\lib\connection.js:92:25)
      at Socket.emit (events.js:375:28)
      at addChunk (internal/streams/readable.js:290:12)
      at readableAddChunk (internal/streams/readable.js:265:9)
      at Socket.Readable.push (internal/streams/readable.js:204: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 NOT NULL, `createdBy` NUMBER, `createdAt` DATETIME NOT NULL, `updatedAt` ' at line 1",
    sql: 'CREATE TABLE IF NOT EXISTS `tasks` (`id` INTEGER NOT NULL auto_increment , `title` VARCHAR(255) NOT NULL, `description` VARCHAR(255) NOT NULL, `status` NUMBER NOT NULL, `createdBy` NUMBER, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY 
(`id`)) ENGINE=InnoDB;',
    parameters: undefined
  },
  original: 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 NOT NULL, `createdBy` NUMBER, `createdAt` DATETIME NOT NULL, `updatedAt` ' at line 1
      at Packet.asError (C:\Users\Kryolos.Hakeem\desktop\vodafone-tech-test\back-end-v2\node_modules\mysql2\lib\packets\packet.js:728:17)
      at Query.execute (C:\Users\Kryolos.Hakeem\desktop\vodafone-tech-test\back-end-v2\node_modules\mysql2\lib\commands\command.js:29:26)
      at Connection.handlePacket (C:\Users\Kryolos.Hakeem\desktop\vodafone-tech-test\back-end-v2\node_modules\mysql2\lib\connection.js:456:32)
      at PacketParser.onPacket (C:\Users\Kryolos.Hakeem\desktop\vodafone-tech-test\back-end-v2\node_modules\mysql2\lib\connection.js:85:12)
      at PacketParser.executeStart (C:\Users\Kryolos.Hakeem\desktop\vodafone-tech-test\back-end-v2\node_modules\mysql2\lib\packet_parser.js:75:16)
      at Socket.<anonymous> (C:\Users\Kryolos.Hakeem\desktop\vodafone-tech-test\back-end-v2\node_modules\mysql2\lib\connection.js:92:25)
      at Socket.emit (events.js:375:28)
      at addChunk (internal/streams/readable.js:290:12)
      at readableAddChunk (internal/streams/readable.js:265:9)
      at Socket.Readable.push (internal/streams/readable.js:204: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 NOT NULL, `createdBy` NUMBER, `createdAt` DATETIME NOT NULL, `updatedAt` ' at line 1",
    sql: 'CREATE TABLE IF NOT EXISTS `tasks` (`id` INTEGER NOT NULL auto_increment , `title` VARCHAR(255) NOT NULL, `description` VARCHAR(255) NOT NULL, `status` NUMBER NOT NULL, `createdBy` NUMBER, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY 
(`id`)) ENGINE=InnoDB;',
    parameters: undefined
  },
  sql: 'CREATE TABLE IF NOT EXISTS `tasks` (`id` INTEGER NOT NULL auto_increment , `title` VARCHAR(255) NOT NULL, `description` VARCHAR(255) NOT NULL, `status` NUMBER NOT NULL, `createdBy` NUMBER, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB;',
  parameters: {}
}
[nodemon] clean exit - waiting for changes before restart



这是我的连接:

const { Sequelize } = require('sequelize');

require('dotenv').config()

const Sequelized = new Sequelize(
  process.env.DATABASE_NAME,
  process.env.USER_NAME,
  process.env.PASSWORD,
  {
    dialect: 'mysql',
    host: process.env.DATABASE_HOST
  }
);

module.exports = Sequelized; 

这是我的应用入口点

const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const router = require('./routes/tasks');

const Sequelized = require('./utiles/database');

const app = express();

require('dotenv').config();

app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));

app.use(router);

Sequelized.sync()
  .then((result) => {
    console.log('result: ', result);
    app.listen(3001, () => console.log('App is Listining on port 3001'));
  })
  .catch((err) => {
    console.log('err: ', err);
  });

这是我的任务模型定义

const { DataTypes } = require('sequelize');
const Sequelized = require('../utiles/database');

const Task = Sequelized.define('task', {
  id: {
    type: DataTypes.INTEGER,
    autoIncrement: true,
    allowNull: false,
    primaryKey: true,
  },
  title: {
    type: DataTypes.STRING,
    allowNull: false,
  },
  description: {
    type: DataTypes.STRING,
    allowNull: false,
  },
  status: {
    type: DataTypes.NUMBER,
    allowNull: false,
  },
  createdBy: {
    type: DataTypes.NUMBER,
    allowNull: true
  }
});

module.exports = Task;

这是我尝试 运行 它

const Task = require("../models/task");

exports.CreateTask = (req, res) => {
    const { title, description, userId } = req.body;

    Task.CreateTask({
        title,
        description,
        createdBy: userId,
        status: 1
    }).then(res => {
        console.log('res: ', res)
    }).catch((err) => {
        console.log('err: ', err);
    })
}

这个问题只在我尝试使用 Task 开始创建任务时发生,我认为这个问题是可以重现的, 肯定会感谢任何帮助, 谢谢

问题是您定义了模型 Taks,并且在最后一段代码中导出了一个名为 CreateTask 的函数。

但是在这个箭头函数中,你尝试创建一个新的 Task 但你又调用了 CreateTask 。而且您还错过了为 titledescription 指定要分配这些值的键是什么。

你应该像这样使用 Task.creat(...

const Task = require("../models/task");

exports.CreateTask = (req, res) => {
    const { title, description, userId } = req.body;

    Task.create({
        title: title,
        description: description,
        createdBy: userId,
        status: 1
    }).then(res => {
        console.log('res: ', res)
    }).catch((err) => {
        console.log('err: ', err);
    })
}