I have a model and migration defined:
module.exports = (sequelize, DataTypes) => {
const user = sequelize.define('user', {
name: DataTypes.STRING,
username: DataTypes.STRING,
email: DataTypes.STRING,
password: DataTypes.STRING,
},
{})
user.associate = function (models) {
// associations can be defined here
}
return user
}
'use strict';
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('users', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
name: {
allowNull: false,
type: Sequelize.STRING
},
username: {
unique: true,
allowNull: false,
type: Sequelize.STRING
},
email: {
allowNull: false,
type: Sequelize.STRING
},
password: {
allowNull: false,
type: Sequelize.STRING
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
down: (queryInterface, Sequelize) => {
return queryInterface.dropTable('users');
}
};
When I try to create a new user user.create({...}) that has duplicate key value(email or username in this case) sequelizes throwns an error as expected and even so it increases de primary key auto-increment value.
Example: I create a new user that has id 1, then I try to create 5 times a new user that has duplicate unique keys(username or email), then when I create a user successfully, the primary key id becomes 6.
Why this happens? The correct would be to follow the order, if error then does not increment, only increment when the user is inserted successfully.