Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize: Unique validation with soft deleted registers

I'm using sequelize, my model 'users', has a field 'email' that has the unique validation. But when i try to create a new register using the same email of a old register soft deleted, the validation triggers and not allow me to continue. Is this a bug, the unique validation need a specific parameter for that or it is supposed to work this way?

Email on model:

email: {    
    type: Sequelize.STRING(191),
    allowNull: false,
    unique: {
       msg: 'Email já cadastrado.'
    },    
    validate: {
       isEmail: {
           msg: 'Formato de email inválido.'
       },
       notEmpty:{
           msg: 'Email deve ser informado.'
       }
    }
}

The version of sequelize i'm using is: 4.17.2

like image 233
Matheus Bueno Avatar asked Sep 12 '25 22:09

Matheus Bueno


1 Answers

This is not a bug - it is enforcing a unique index on the database table. A "soft" delete just marks the record as deleted (isDeleted=true for example) but it is not actually removed from the database table. Assuming the database did allow you to create a duplicate value in the unique column, this would then cause a problem if you ever un-deleted the soft-deleted item with the conflicting name.

The functionality it seems you are going for is possible, but you will need to enforce the logic programmatically in your app rather than at the database level.

like image 179
doublesharp Avatar answered Sep 16 '25 09:09

doublesharp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!