Database Model's meta data should be defined in models file or migration file?

巧了我就是萌 提交于 2020-06-28 06:57:11

问题


Using sequelize init I generated a model with a migration.

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
      }
    });
  },
...

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

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

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).


回答1:


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

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


来源:https://stackoverflow.com/questions/62428876/database-models-meta-data-should-be-defined-in-models-file-or-migration-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!