Search code examples
node.jsmigrationsequelize.jsunique

SequelizeUniqueConstraintError: Validation error


I am using sequelize and node.js. I have one column that want change it's type to unique, when I want run the migration I have this err , How can I solve it?

ERROR: SequelizeUniqueConstraintError: Validation error

this is my code :


up: (queryInterface, Sequelize) => {
    return Promise.all([
      queryInterface.changeColumn('PersonalInfo', 'ssn', {type: Sequelize.STRING, unique: true
      }),
      queryInterface.changeColumn('PersonalInfoDraft', 'ssn', {type: Sequelize.STRING, unique:true
      })
    ])
  }

Solution

  • You need to make sure these columns don’t have duplicate data first. If not, it will fail to change them to unique as it can’t satisfy the rule

    Here is an example post on how to delete duplicate rows and keep one instance of each row. Make sure to backup your data before running deletes just in case.

    https://stackoverflow.com/a/63735751/14167216