node.js - 使用增量函数进行序列化验证

标签 node.js validation sequelize.js

有一个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
   }
}

这是否可能与增量是在数据库中完成的事实有关?我可以做一些事情来添加验证吗?

最佳答案

验证是针对实例(在您的应用程序中)而不是针对数据库进行的。

增量 API 很特殊,因为它直接在数据库中而不是在实例上更新值

来自https://sequelize.org/master/class/lib/model.js~Model.html#static-method-increment (强调我的)

Increment the value of one or more columns. This is done in the database, which means it does not use the values currently stored on the Instance. The increment is done using a SET column = column + X WHERE foo = 'bar' query. To get the correct value after an increment into the Instance you should do a reload.

如果您想增加并完成验证,您可以:

关于node.js - 使用增量函数进行序列化验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67643436/

相关文章:

javascript - 如何在同一个函数中处理不同的可选回调?

javascript - 云函数超时后继续执行

sequelize.js - Promise.method() 抛出未处理的拒绝 - 为什么?

node.js - 嵌套包含 Sequelize

node.js - 如何隐藏mongo终端的输出(Node.Js)

node.js - Mongoose :更新特定文档数组的元素

php - ZF2 表单验证 - 不重叠的日期和时间

codeigniter - 如何让 form_validation 在 Codeigniter 中正常工作

php - 在 PHP 中转义粘性表单值中的双引号

undefined - sequelize BulkCreate 无法读取未定义的属性 'set'