未处理的拒绝SequelizeUniqueConstraintError:验证错误

Fil*_*ano 9 javascript mysql node.js sequelize.js

我收到这个错误:

Unhandled rejection SequelizeUniqueConstraintError: Validation error
Run Code Online (Sandbox Code Playgroud)

我怎样才能解决这个问题?

这是我的models/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;
};
Run Code Online (Sandbox Code Playgroud)

这是我的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');
                        });

                } 
            });



    });
Run Code Online (Sandbox Code Playgroud)

dou*_*arp 18

呼叫User.create()返回a 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);
});
Run Code Online (Sandbox Code Playgroud)


Ric*_*ado 7

如果您创建了一个唯一约束,请检入您的数据库,我的猜测是您为其添加了一些值unique: true并对其进行了更改,但是sequelize无法从数据库中删除它的约束.


ahe*_*rog 6

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

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

我已经在我的数据库中植入了记录,即使这些记录的 id 也设置为自动递增,200 条记录的 id 分散在 1 到 2000 之间,但数据库的自动递增序列设置为从 1 开始。通常序列中的下一个id未被使用,但偶尔它已经被占用,并且数据库会返回此错误。

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

  • 谢谢!。我只是惊讶于 sequelize 如何在 PG 上没有一个透明的解决方案,还有一个违反直觉的错误代码。 (2认同)

jlh*_*jlh 5

当使用 SQLite 作为数据库时,Sequelize(当前为 5.21.5)会抛出SequelizeUniqueConstraintError每个约束错误,即使它与唯一索引无关。一个示例是插入NULL到不可为空的列中。因此,在调试此异常时,请务必检查其他类型的错误。