我尝试使用一些自定义验证逻辑在 sequelize 中创建一个模型(比如有 3 个属性,attrA、B 和 C)。 This tutorial 帮助我完成了大部分设置:
const Model = Sequelize.define('model', {
attrA: { type: Sequelize.STRING },
attrB: { type: Sequelize.STRING },
attrC: { type: Sequelize.STRING },
}, {
validate: {
someValidationLogic() {
// Do something with attrA,B,C
// if (this.attrA ... this.attrB ... this.attrC) throw new Error..
}
}
})
但是,在应用程序逻辑中,仅需要更新 3 个属性(A 和 B)中的 2 个:
Model.update(
{
attrA: 'foo',
attrB: 'bar'
}, {
where: {
id: 1,
},
returning: true,
})
这导致在调用自定义验证逻辑时,在函数中访问的
this
对象中, attrA
中仅定义了 attrB
和 this
,而 attrC 未定义。这会导致验证逻辑失败,因为无法读取 attrC。有什么方法可以让对象从 someValidationLogic()
可见以填充所有属性?或者这个“验证”根本不应该是验证逻辑而应该在应用程序级别完成?
最佳答案
您的验证逻辑可以考虑未定义 attrC
的可能性:
validate: {
someValidationLogic() {
if (this.attrA !== 'undefined' && this.attrA === 'forbidden value' ) {
// throw new Error
}
}
}
但是,如果您的验证包括根据当前数据库值检查提供的值,那么您最好在应用程序层处理此问题:首先恢复当前数据库记录,根据需要对其进行操作,然后将其保存到数据库中。
关于javascript - Sequelize 自定义验证 - 无法访问实体中的所有字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53899237/