【发布时间】:2019-01-29 20:53:49
【问题描述】:
我正在编写一个应用程序并使用 Sequelize 作为 ORM。我遇到过这个问题:我有一个模型,它有 2 个字段(为简单起见,实际上有更多字段),它们相互依赖,就像这样:
const Application = sequelize.define('application', {
visa_required: {
type: Sequelize.BOOLEAN,
allowNull: false,
defaultValue: false
},
visa_passport_number: {
allowNull: false,
type: Sequelize.STRING,
defaultValue: '',
validate: {
shouldBeSetIfVisaRequired(val) {
if (this.visa_required && (typeof val !== 'string' || val.trim().length === 0)) {
throw new Error('Please fill in this field.');
}
}
}
}
});
因此,如果设置了visa_required 字段,则还应设置visa_passport_number。
问题是,当我将true 传递给visa_required 并将null 传递给visa_passport_number 时,它会因application.visa_passport_number cannot be null 错误而失败。当我不传递此值时,它会正常(但保存为空字符串)。
我可以将allowNull: true 作为visa_passport_number 的参数传递,但是如果我将此值设置为null,则此验证将被忽略。
那么,我怎样才能实现我想要实现的目标呢?
【问题讨论】:
标签: node.js sequelize.js