[英]Unhandled rejection SequelizeUniqueConstraintError: Validation error
我收到此错误:
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');
});
}
});
});
对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);
}
如果您创建了唯一约束,请检查您的数据库,我的猜测是您将一些值设置为unique: true
并更改了它,但是 sequelize 无法从您的数据库中删除它的约束。
我的 QA 数据库有这个问题。 有时新记录会保存到数据库中,有时会失败。 在我的开发工作站上执行相同的过程时,它每次都会成功。
当我发现错误(根据@doublesharp 的好建议)并将完整结果打印到控制台时,它确认违反了唯一约束 - 特别是主键 id 列,该列被设置为默认为自动递增的值。
我已经在我的数据库中植入了记录,即使这些记录的 id 也设置为自动递增,200 条记录的 id 分散在 1 到 2000 之间,但数据库的自动递增序列设置为从 1 开始。通常序列中的下一个id未被使用,但偶尔它已经被占用,并且数据库会返回此错误。
我使用这里的答案将序列重置为在最后一个种子记录之后开始,现在它每次都有效。
当使用 SQLite 作为数据库时,Sequelize(当前为 5.21.5)在每个约束错误上抛出SequelizeUniqueConstraintError
,即使它与唯一索引无关。 一个例子是将NULL
插入到不可为空的列中。 所以在调试这个异常的时候一定要检查其他类型的错误。
以@Ricardo Machado 的回答为基础,如果您向模型添加unique:true
并且现有表中已经有在此新约束下不允许的值,您将收到此错误。 要修复,您可以手动删除行或删除表,然后 Sequelize 再次构建它。
如果您在 Sequelize 中偶然发现此Validation error
:检查填充(创建)表的查询是否执行一次。
我的 Nest.js 应用程序没有正确设置并执行了两次相同的命令,从而违反了唯一约束。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.