John Kevin M. Basco John Kevin M. Basco - 5 months ago 137
Node.js Question

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?

Answer

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: [
    { name: 'unique_name', unique: true, fields: [sequelize.fn('lower', sequelize.col('name')) }
  ]
});