在MySQL中使用sequelize自动增加id

时间:2015-11-18 08:36:42

标签: mysql node.js sequelize.js

我在NodeJS中有以下模型,包括sequelize和MySQL数据库:

var Sequelize = require('sequelize');
var User = sequelize.define('user', {        
        id: {
            type: Sequelize.INTEGER,
            autoIncrement: true,
            primaryKey: true
        },
        ...
};

我正在尝试使用以下代码向我的数据库添加新用户:

sequelize.transaction().then(function(t) {
        User.create({/* User data without id */}, {
            transaction: t
        }).then(function() {
            t.commit();
        }).catch(function(error) {
            t.rollback();
        });
    });

之后,我收到了下一个错误:

Executing (47f19f7b-a02d-4d72-ba7e-d5045520fffb): START TRANSACTION;
Executing (47f19f7b-a02d-4d72-ba7e-d5045520fffb): SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
Executing (47f19f7b-a02d-4d72-ba7e-d5045520fffb): SET autocommit = 1;
Executing (47f19f7b-a02d-4d72-ba7e-d5045520fffb): INSERT INTO `user` (`id`, /* next fields */) VALUES (DEFAULT, /* next values */);
Executing (47f19f7b-a02d-4d72-ba7e-d5045520fffb): ROLLBACK;

错误信息:

[SequelizeDatabaseError: ER_NO_DEFAULT_FOR_FIELD: Field 'id' doesn't have a default value]
  name: 'SequelizeDatabaseError',
  message: 'ER_NO_DEFAULT_FOR_FIELD: Field \'id\' doesn\'t have a default value'

但是,如果我手动设置id值,它会起作用。似乎sequelize试图在id字段中设置默认值,而不是设置自动增量整数。我在我的数据库中也将此字段定义为autoIncrement。

我该如何插入?我是否必须手动设置ID?

修改

这是我的表定义:

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `uid` varchar(9) NOT NULL,
  `name` varchar(20) NOT NULL,
  `email` varchar(30) DEFAULT NULL,
  `birthdate` date NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uid_UNIQUE` (`uid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

2 个答案:

答案 0 :(得分:16)

您必须确保自己根本不发送id密钥。

我做了一个快速的最小测试,看起来效果很好:

var Sequelize = require('sequelize');
var sequelize = new Sequelize('cake3', 'root', 'root', {
    define: {
        timestamps: false
    },
});
var User = sequelize.define('user1', {        
        id: {
            type: Sequelize.INTEGER,
            autoIncrement: true,
            primaryKey: true
        },
        name: {
            type: Sequelize.STRING
        }
});

sequelize.transaction().then(function(t) {
    User.create({name:'test'}, {
        transaction: t
    }).then(function() {
        t.commit();
    }).catch(function(error) {
        console.log(error);
        t.rollback();
    });
});

表转储:

CREATE TABLE `user1s` (
  `id` int(11) NOT NULL,
  `name` varchar(20) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
ALTER TABLE `user1s`
  ADD PRIMARY KEY (`id`);
ALTER TABLE `user1s`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=1;

答案 1 :(得分:0)

在迁移中,添加以下代码行:

await queryInterface.sequelize.query("ALTER TABLE table_name AUTO_INCREMENT = 1000000;");