Reputation:
I updated the sequelize package in our project in two steps from 4.41.0 over 5.22.2 to 6.6.5. With 5.22.2 everythings OK (besides, "pg" and "sequelize-fixtures" had to be updated to 7.6.0 respectively 1.2.0). But with v6.6.5 ...
ProductCompatibility.create({
product_id: someNumber,
compatible_product_id: someOtherNumber,
});
... Sequelize creates the record but does not set the default primary key "id". The Model:
module.exports = (sequelize, Sequelize) => {
const ProductCompatibility = sequelize.define('ProductCompatibility', {
product_id: { type: Sequelize.INTEGER },
compatible_product_id: { type: Sequelize.INTEGER },
created_at: { type: Sequelize.DATE },
updated_at: { type: Sequelize.DATE },
}, {
tableName: 'product_compatibilities',
timestamps: true,
createdAt: 'created_at',
updatedAt: 'updated_at',
});
return ProductCompatibility;
};
When I add this to the Model, ...
const ProductCompatibility = sequelize.define('ProductCompatibility', {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true,
},
...
..., the id will be set.
That's OK for me, but I'd like to know, why the default behavior - setting the standard primary key id and auto increment it - does not work anymore.
Upvotes: 1
Views: 1162
Reputation: 606
Sequelize creates primary key fields automatically now. If you want to rename the id column name to product_id you'd need to define it in the model as the primary key or if you want to use a different datatype id. But if you just want a int auto increment PK you can leave out the field entirely.
module.exports = Model = (sequelize, DataTypes) => {
const Model = sequelize.define('Model', {
// To just have a "id" column that is an int and auto increment you can leave out the id field
custom_model_id: {
type: DataTypes.UUID, // I like to use UUIDs
defaultValue: DataTypes.UUIDV4,
primaryKey: true
},
field: DataTypes.STRING
})
return Model
}
Upvotes: 1