node.js - Sequelize 中的 UUID 主键给出了 : (node:6927) UnhandledPromiseRejectionWarning: SequelizeDatabaseError: Field 'id' doesn't have a default value)

标签 node.js express sequelize.js uuid

我知道这是一个很好的报告问题,但它没有得到很好的记录,并且解决方法不像“ 从 MySQL 删除严格模式”那样“ 专业
我想在我的应用程序中使用 sequelize 将 uuidv4 设置为主键,但我收到了 (node:6927) UnhandledPromiseRejectionWarning: SequelizeDatabaseError: Field 'id' doesn't have a default value)在迁移中设置它会给我这个错误,但是如果我将它添加到我的 Controller 中,它似乎可以工作。
我的问题是,我的解决方法是正确的解决方案还是有更好的方法?
我的迁移

'use strict';
const {Model, DataTypes} = require('sequelize');
const uuidv4 = require('uuid').v4;
module.exports = {
  up: async (queryInterface, DataTypes) => {
    await queryInterface.createTable('Etudiant', {
      id: {
        type: DataTypes.UUID,
        defaultValue: uuidv4(),  // why does this not work ?
        unique: true,
        primaryKey: true,
      },
      nom: {
        type: DataTypes.STRING,
        allowNull: false
      },
      prenom: {
        type: DataTypes.STRING,
        allowNull: false
      },
      mail: {
        type: DataTypes.STRING,
        allowNull: false
      },
      convention: {
        type: DataTypes.UUID,
        defaultValue: DataTypes.UUIDV4,
        allowNull: false
      }
    });
  },
  down: async (queryInterface, DataTypes) => {
    await queryInterface.dropTable('Etudiants');
  }
我的路线:
const express = require('express');
const models = require('./src/database/models');
const Sequelize = require('sequelize');
const db = require('./src/database/db');
const uuidv4 = require('uuid').v4;


const app = express();


app.use(express.json());

app.get('/', (req, res) =>{
    return models.Etudiant.create({
        //id : uuidv4(),    // this is where I think is not a propersolution
        nom: "AL HR",
        prenom: "Malek",
        mail: "mail@gmail.com",
        convention: "4rzd-3be2lk-4glma"
    });
});


app.listen(3000, console.log('G'));

最佳答案

defaultValue 是与数据库级别的默认值相关的表属性。在您的代码中,这被确定为一个值(由 uuid() 函数返回)并且确实不应该起作用。
为了解决这个问题,你可能需要在数据库中使用一些 uuid 扩展来生成这个 uuid,使用 Sequelize.fn

id:   {
        type: DataTypes.UUID,
        defaultValue: Sequelize.fn('UUID()'), // this UUID() is a mysql function, not a node_module.
        unique: true,
        primaryKey: true,
      },

关于node.js - Sequelize 中的 UUID 主键给出了 : (node:6927) UnhandledPromiseRejectionWarning: SequelizeDatabaseError: Field 'id' doesn't have a default value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67877374/

相关文章:

node.js - axios 和 Azure Application Insights 的问题

javascript - 如何从 Heroku 上的 Node.js 应用程序中的子文件夹重定向到静态 javascript 应用程序?

javascript - 有什么方法可以重新启动 vercel 上托管的 Nodejs 应用程序吗?

sequelize.js - 如何在 sequelize 中连接表

mysql - GraphQL 内部的 Sequelize 不会连接连接表

javascript - 在 NodeJS 中压缩视频文件

node.js - 未处理的拒绝 SequelizeHostNotFoundError : getaddrinfo ENOTFOUND in sequelize

express - 如何在 Jest 中测试 Express 中间件的 `verify`

javascript - 我正在尝试使用 multer 接收视频文件并将其保存在服务器上

count - 如何在 sequelize 中找到没有任务的用户数