【问题标题】:Database Model's meta data should be defined in models file or migration file?数据库模型元数据应该在模型文件或迁移文件中定义吗?
【发布时间】:2020-06-17 20:29:52
【问题描述】:

使用sequelize init,我生成了一个带有迁移的模型。

在model.js里面只有每个属性的类型的定义,e.g.

const User = sequelize.define('User', {
    firstName: DataTypes.STRING,
    lastName: DataTypes.STRING,
    email: DataTypes.STRING,
    password: DataTypes.STRING
  }, {});

在迁移文件中,还有其他选项,例如

...
up: (queryInterface, Sequelize) => {
    return queryInterface.createTable('Users', {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER
      },
      firstName: {
        type: Sequelize.STRING
      },
      lastName: {
        type: Sequelize.STRING
      },
      email: {
        type: Sequelize.STRING,
      },
      password: {
        type: Sequelize.STRING
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE
      }
    });
  },
...

例如,如果我想让电子邮件独一无二,我会将电子邮件属性更改为:

      email: {
        type: Sequelize.STRING,
        unique: true
      },

我的问题是在 model.js 文件中包含这些额外的属性选项是好主意还是坏主意,或者只保留属性的定义(types)来保持简单。

【问题讨论】:

    标签: mysql node.js orm model sequelize.js


    【解决方案1】:

    是的,你可以这样做,你也可以像这样为值定义验证。

    所以,您不必每次都在 api 调用中查找 email_id 是否已经退出。

    email: {
          type: Sequelize.STRING(18),
          validate: {
            isUnique(value, next) {
              user.find({
                where: { email: value },
                attributes: ['id']
              }).done((user) => {
                if (user)
                  return next('errors.email.unique');
    
                next();
              });
            }
          }
    

    【讨论】:

      猜你喜欢
      • 2012-11-18
      • 1970-01-01
      • 2012-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多