简体   繁体   中英

How to add a case-insensitive unique constraint in a SequelizeJS Model when using Postgresql?

var Model = sequelize.define('Company', {
  name: {
    type: DataTypes.STRING,
    unique: true
  }
}

In the above example, unique: true is case sensitive. It allows both "sample" and "Sample" to be saved in the db. Is there a built-in way to do this in sequelize without having to write a custom validator?

I'd suggest adding a functional unique index as seen here: http://www.postgresql.org/message-id/c57a8ecec259afdc4f4caafc5d0e92eb@mitre.org

var Model = sequelize.define('Company', {
  name: {
    type: DataTypes.STRING
  }
}, 
{
  indexes: [
    { 
      unique: true,   
      name: 'unique_name',  
      fields: [sequelize.fn('lower', sequelize.col('name'))]   
    }
  ]
});

01AUG2022 update. I stumbled across this while trying to solve the same problem and I come with good news! As long as you're using Postgres or SQLite you can set your data type to type: DataTypes.CITEXT and your values will retain their case in the database while also giving a Validation error if you try to add another entry regardless of case.

TLDR: testuser and TestUser will throw a validation error if the column type is CITEXT .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM