ho il seguente modello in NodeJS con sequelize e un database MySQL:Incremento automatico id con sequelize in MySQL
var Sequelize = require('sequelize');
var User = sequelize.define('user', {
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
primaryKey: true
},
...
};
Sto cercando di aggiungere un nuovo utente al mio databse con il codice qui sotto:
sequelize.transaction().then(function(t) {
User.create({/* User data without id */}, {
transaction: t
}).then(function() {
t.commit();
}).catch(function(error) {
t.rollback();
});
});
Dopo di che, io sono sempre l'errore successivo:
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;
E il messaggio di errore:
[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'
Tuttavia, se si imposta manualmente il valore id, funziona. Sembra che il sequelize stia cercando di impostare un valore predefinito nel campo id, invece di impostare un numero intero di autoincremento. Ho definito questo campo anche autoIncrement nel mio database.
Come posso fare questo inserimento? Devo impostare l'id manualmente?
EDIT
Questa è la mia definizione di tabella:
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;
cosa fa la struttura del database simile? Forse non è impostato correttamente in MySQL stesso? – Andrius
@Andrius, ho aggiornato la mia domanda per aggiungere questa informazione – Genzotto