【问题标题】:Unhandled rejection SequelizeUniqueConstraintError: Validation error未处理的拒绝 SequelizeUniqueConstraintError:验证错误
【发布时间】:2017-04-04 05:06:34
【问题描述】:

我收到此错误:

Unhandled rejection SequelizeUniqueConstraintError: Validation error

我该如何解决这个问题?

这是我的模型/user.js

"use strict";

module.exports = function(sequelize, DataTypes) {
  var User = sequelize.define("User", {
    id:  { type: DataTypes.INTEGER, autoIncrement: true, primaryKey: true},
    name: DataTypes.STRING,
    environment_hash: DataTypes.STRING
  }, {
    tableName: 'users',
    underscored: false,
    timestamps: false
  }

  );

  return User;
};

这是我的 routes.js:

app.post('/signup', function(request, response){

        console.log(request.body.email);
        console.log(request.body.password);

        User
        .find({ where: { name: request.body.email } })
            .then(function(err, user) {
                if (!user) {
                        console.log('No user has been found.');

                        User.create({ name: request.body.email }).then(function(user) {
                            // you can now access the newly created task via the variable task
                            console.log('success');
                        });

                } 
            });



    });

【问题讨论】:

    标签: javascript mysql node.js sequelize.js


    【解决方案1】:

    如果您从 Sequelize 中偶然发现此 Validation error:请检查填充(创建)表的查询是否已执行一次。

    我的 Nest.js 应用程序未正确设置并执行了两次相同的命令,因此违反了唯一约束。

    【讨论】:

      【解决方案2】:

      当使用 SQLite 作为数据库时,Sequelize(当前为 5.21.5)在每个约束错误上抛出 SequelizeUniqueConstraintError,即使它与唯一索引无关。一个例子是将NULL 插入到不可为空的列中。所以在调试这个异常的时候一定要检查其他类型的错误。

      【讨论】:

        【解决方案3】:

        User.create() 的调用返回一个Promise.reject(),但没有.catch(err) 来处理它。如果不捕获错误并且不知道输入值,就很难说出验证错误是什么——request.body.email 可能太长,等等。

        捕获 Promise 拒绝以查看错误/验证详细信息

        User.create({ name: request.body.email })
        .then(function(user) {
            // you can now access the newly created user
            console.log('success', user.toJSON());
        })
        .catch(function(err) {
            // print the error details
            console.log(err, request.body.email);
        });
        

        更新,因为现在是 2019 年,您可以使用 async/await

        try {
          const user = await User.create({ name: request.body.email });
          // you can now access the newly created user
          console.log('success', user.toJSON());
        } catch (err) {
          // print the error details
          console.log(err, request.body.email);
        }
        

        【讨论】:

        • 使用 try/catch 选项,有趣的是,它会进入 catch 部分并显示“TypeError: (intermediate value) is not iterable”,即使记录已插入表中
        • @golimar 这可能是对toJSON() 的调用的问题 - 你能把它排除在外并设置一个断点来调试吗?
        • 谢谢,这样做我意识到我将 create() 输出分配给 2 个变量,它只返回 1 个值(相当误导的错误消息)
        【解决方案4】:

        以@Ricardo Machado 的回答为基础,如果您将unique:true 添加到模型中,并且现有表中已有在此新约束下不允许的值,您将收到此错误。要修复,您可以手动删除行或删除表,以便 Sequelize 再次构建它。

        【讨论】:

          【解决方案5】:

          如果您创建了 Unique Constraint,请检查您的数据库,我的猜测是您为 unique: true 设置了一些值并对其进行了更改,但 sequelize 无法从您的数据库。

          【讨论】:

            【解决方案6】:

            我的 QA 数据库遇到了这个问题。有时一条新记录会保存到数据库中,有时它会失败。在我的开发工作站上执行相同的过程时,每次都会成功。

            当我发现错误(根据@doublesharp 的好建议)并将完整结果打印到控制台时,它确认违反了唯一约束 - 特别是主键 id 列,该列默认设置为自动递增价值。

            我已经在我的数据库中植入了记录,尽管这些记录的 id 也设置为自动增量,但 200 条记录的 id 分散在 1 到 2000 之间,但数据库的自动增量序列设置为从1. 通常顺序的下一个id没有被使用,但偶尔已经被占用了,数据库会返回这个错误。

            我使用答案here 将序列重置为在我的最后一条种子记录之后开始,现在它每次都有效。

            【讨论】:

            • 谢谢!。我只是惊讶于 sequelize 在 PG 上没有一个透明的解决方案,还有一个违反直觉的错误代码。
            猜你喜欢
            • 2020-09-24
            • 2017-06-08
            • 1970-01-01
            • 2022-08-22
            • 1970-01-01
            • 2019-10-27
            • 2019-04-09
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多