Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unhandled rejection SequelizeUniqueConstraintError: Validation error

I'm getting this error:

Unhandled rejection SequelizeUniqueConstraintError: Validation error

How can I fix this?

This is my models/user.js

"use strict";

module.exports = function(sequelize, DataTypes) {
  var User = sequelize.define("User", {
    id:  { type: DataTypes.INTEGER, autoIncrement: true, primaryKey: true},
    name: DataTypes.STRING,
    environment_hash: DataTypes.STRING
  }, {
    tableName: 'users',
    underscored: false,
    timestamps: false
  }

  );

  return User;
};

And this is my routes.js:

app.post('/signup', function(request, response){

        console.log(request.body.email);
        console.log(request.body.password);

        User
        .find({ where: { name: request.body.email } })
            .then(function(err, user) {
                if (!user) {
                        console.log('No user has been found.');

                        User.create({ name: request.body.email }).then(function(user) {
                            // you can now access the newly created task via the variable task
                            console.log('success');
                        });

                } 
            });



    });
like image 451
Filipe Ferminiano Avatar asked Nov 20 '16 21:11

Filipe Ferminiano


2 Answers

The call to User.create() is returning a Promise.reject(), but there is no .catch(err) to handle it. Without catching the error and knowing the input values it's hard to say what the validation error is - the request.body.email could be too long, etc.

Catch the Promise reject to see the error/validation details

User.create({ name: request.body.email })
.then(function(user) {
    // you can now access the newly created user
    console.log('success', user.toJSON());
})
.catch(function(err) {
    // print the error details
    console.log(err, request.body.email);
});

Update, since it's 2019 and you can use async/await

try {
  const user = await User.create({ name: request.body.email });
  // you can now access the newly created user
  console.log('success', user.toJSON());
} catch (err) {
  // print the error details
  console.log(err, request.body.email);
}
like image 80
doublesharp Avatar answered Nov 03 '22 00:11

doublesharp


Check in your database if you have an Unique Constraint created, my guess is that you put some value to unique: true and changed it, but sequelize wasn't able to delete it's constraint from your database.

like image 21
Ricardo Machado Avatar answered Nov 02 '22 22:11

Ricardo Machado