【发布时间】:2021-05-22 16:25:49
【问题描述】:
有一个 sequelize 函数允许将一个值递增一个数字,该数字可以为负数或递减数,我想确保该列始终为正数或 0,所以我在我的模型中添加了一个验证器:
module.exports = function (sequelize, DataTypes) {
var ProductVariant = sequelize.define('ProductVariant', {
id: {
type: DataTypes.INTEGER(11),
allowNull: false,
primaryKey: true,
autoIncrement: true
},
ProductId: {
type: DataTypes.STRING(45),
field: 'product_id',
allowNull: false,
primaryKey: true,
references: {
model: 'product',
key: 'id'
}
},
image: {
type: DataTypes.INTEGER(11),
allowNull: true
},
price: {
type: DataTypes.DECIMAL(6, 2),
allowNull: false
},
qty_stock: {
type: DataTypes.INTEGER(11),
allowNull: false,
defaultValue: 0
},
createdAt: {
type: 'TIMESTAMP',
allowNull: true,
field: 'creation_date'
},
updatedAt: {
type: 'TIMESTAMP',
field: 'last_updated',
allowNull: true
},
},
{
tableName: 'variants',
hooks: {
beforeValidate: function(variant, options) {
if (variant.qty_assigned < 0) {
throw new Error('Not valid');
}
}
}
});
ProductVariant.associate = function (models) {
ProductVariant.belongsTo(models.Product)
},
{
indexes:
[{
unique: true,
fields: ['product_id']
}]
}
return ProductVariant;
};
但是当我这样做时:
await ProductVariant.increment({ qty_assigned: -100 }, {
where: { id: { [Op.eq]: variantId } },
transaction: t
});
我在不检查验证的情况下工作并更新值。我也试过:
qty_stock: {
type: DataTypes.INTEGER(11),
allowNull: false,
defaultValue: 0,
validate: {
min: 0
}
}
这可能与增量是在数据库中完成的事实有关吗?我可以做些什么来添加验证吗?
【问题讨论】:
标签: node.js validation sequelize.js