序列化重复键值违反唯一约束

时间:2018-10-26 08:28:53

标签: node.js postgresql sequelize.js on-duplicate-key

我正在研究nodeJs和postgresql。 我面临错误

  

重复的键值违反了唯一约束\“ AuthoriseDates_pkey \”   密钥(id)=(371)已经存在。

我将列ID设置为autoIncrement: true,不明白为什么会这样 列的最大ID为647,但现在我无法在此表中插入记录。

这是迁移代码:

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');
  },
};

这是型号:

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;
};

这是代码插入:

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);
        });

0 个答案:

没有答案