Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unique email address with Sequelize

I'm running ExpressJS with Sequelize/MySQL and trying very hard to get a simple validator check working for unique email address.

Here is my user model. And for the life of me I don't understand why this is allowing records that have duplicate email address. Surely the email.unique=true would be preventing this.

'use strict';
module.exports = (sequelize, DataTypes) => {
  var User = sequelize.define('User', {
    firstName: DataTypes.STRING,
    lastName: DataTypes.STRING,
    email: {
      type: DataTypes.STRING,
      allowNull: false,
      unique: true,
      validate: {
        isEmail: {
          msg: "Must be a valid email address",
        }
      }
    }
  }, {
    indexes: [{
      fields: ['email'],
      unique: true,
    }]
  });
  return User;
};

Any help appreciated.

EDIT: As requested here is the controller code for create user.

const User = require('../models').User;

exports.create = (req, res) => {
  User.create( req.body )
  .then( user => {
    res.json( user );
  })
  .catch( errors => {
    res.json({ errors: errors.errors });
  });
};
like image 833
Fraser Avatar asked Nov 27 '25 11:11

Fraser


1 Answers

One way to solve this is by using sequelize.sync() to create your table according to the schema specified in the model if the table exists then you should pass {force: true} to the sync method, the table will be dropped and a new one will be created.

though using sequelize.sync() is not highly recommended especially in production due to issues with migration files etc, you can google than for more details.

like image 74
Dhouibi iheb Avatar answered Nov 29 '25 02:11

Dhouibi iheb



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!