数据库模型的元数据应该在模型文件还是迁移文件中定义? [英] Database Model's meta data should be defined in models file or migration file?

查看:92
本文介绍了数据库模型的元数据应该在模型文件还是迁移文件中定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用sequelize init我生成了带有迁移的模型.

Using sequelize init I generated a model with a migration.

在model.js内部,只有每个属性类型的定义,例如

Inside model.js there is only the definition of the type of each attribute, e.g.

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

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

In migration file, there are additional options e.g.

...
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属性更改为:

If for example I want to make email unique, I would change the email attribute to:

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

我的问题是在model.js文件中还包含属性的那些额外选项是好还是坏的主意,还是仅保留属性的定义(types)使其简单即可.

My question is whether is a good or bad idea to also include those extra options of attributes inside model.js file or just keep it simple by keeping only the definitions of the attributes (the types).

推荐答案

是的,您可以执行此操作,也可以为此类值定义验证.

yes , you can do it and also you can define validation for the value like this .

因此,您不必每次都在api调用中找到email_id已经退出或未退出的情况.

so , you don't have to find every time that email_id is already exits or not in api call .

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();
          });
        }
      }

这篇关于数据库模型的元数据应该在模型文件还是迁移文件中定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆