• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
正在输入>
博客园    首页    新随笔    联系   管理    订阅  订阅

sequelize中model的使用

/* jshint indent: 2 */
let MD5 = require('crypto').createHash('md5');
module.exports = function (sequelize, DataTypes) {
  return sequelize.define('Account', {
    id: {
      type: DataTypes.INTEGER(11),
      allowNull: false,
      primaryKey: true,
      autoIncrement: true
    },
    name: {
      type: DataTypes.STRING(255),
      allowNull: true,
      // 从数据库查询到数据,经过以下处理后给用户
      get() {
        return "dear " + this.getDataValue('name');
      }
    },
    age: {
      type: DataTypes.INTEGER(11),
      allowNull: true,

      // 数据校验返回异常 customFunc自定义的校验
      validate: {
        max: {
          args: 100,
          msg: "age is larger"
        },
        min: {
          args: 1, 
          msg: 'age is small'
        },
        customFunc(val) {
          if (val === 50) {
            console.log('dddd');
            throw new Error('Only even values are allowed!')
          }
        }

      }
    },
    passwd: {
      type: DataTypes.STRING(255),
      allowNull: true,
      // 当插入或者修改时,经过以下处理后再写入数据库
      set(val) {
        val = MD5.update(val).digest('hex');
        this.setDataValue("passwd", val);
      }

    }
  }, {
    tableName: 'account',

    // setterMethods,getterMethods这个是相当与在存取时都添加了changeName这个虚拟字段
    setterMethods: {
      changeName(val) {
        return this.setDataValue('name', val.slice(0, -1));
      }
    },
    getterMethods: {
      changeName() {
        return this.name + 'changeName';
      }
    }
  });
};
posted @ 2019-12-20 18:35  正在输入>  阅读(1192)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3