2

I am working on nodeJs, and postgresql. I am facing with an error

duplicate key value violates unique constraint \"AuthoriseDates_pkey\" Key (id)=(371) already exists.

I set the column id is autoIncrement: true, don't understand why this happens the max id of columns is 647 but now I cannot insert a record in this table.

here is migrate code :

module.exports = {
  up(queryInterface, Sequelize) {
    return queryInterface.createTable('AuthoriseDates', {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER,
      },
      userId: {
        type: Sequelize.INTEGER,
        references: { model: 'Users', key: 'id' },
      },
      lastAuthorise: {
        type: Sequelize.DATE,
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE,
        defaultValue: Sequelize.fn('NOW'),
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE,
        defaultValue: Sequelize.fn('NOW'),
      },
    });
  },
  down(queryInterface) {
    return queryInterface.dropTable('AuthoriseDates');
  },
};

here is models:

module.exports = (sequelize, DataTypes) => {
  const authoriseDate = sequelize.define('AuthoriseDate', {
    id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
    userId: DataTypes.INTEGER,
    lastAuthorise: DataTypes.DATE,
  });

  authoriseDate.associate = (models) => {
    // associations can be defined here
    authoriseDate.belongsTo(models.User, { foreignKey: 'userId', });
  };

  return authoriseDate;
};

here is code insert:

models.AuthoriseDate.create({
          userId: userId,
          lastAuthorise: new Date().toISOString(),
        }).then((create) => {}).catch((error) => {
          loggerServer.err('error ', error);
          loggerServer.log('debug', { error: error });
          return res.status(500).json(result);
        });
bereket gebredingle
  • 12,064
  • 3
  • 36
  • 47
beginerdeveloper
  • 785
  • 4
  • 17
  • 43
  • is it possible to have this id already created by running test scripts / testing things out and never deleting it? try running `delete from authoriseDate where id = 371` if you're this is just dev data you're playing around with. – Andrei Oct 26 '18 at 12:14

0 Answers0