[英]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.