I'm learning Sequelize and there is something that I found quite strange, so I think that I'm doing something wrong.
This is my migration for a simple Posts
table :
'use strict';
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('Posts', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
title: {
type: Sequelize.STRING,
allowNull: false,
},
content: {
type: Sequelize.TEXT,
allowNull: false,
},
authorId: {
type: Sequelize.INTEGER,
onDelete: 'CASCADE',
allowNull: false,
references: {model: 'Users', key: 'id'}
},
publishedAt: {
type: Sequelize.DATE,
allowNull: true
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
down: (queryInterface, Sequelize) => {
return queryInterface.dropTable('Posts');
}
};
Another little question here, do I have to specify allowNull: false
for the title and the content if I don't want them to be null. I think yes, but many projects I saw don't specify it.
This is the Post
model :
'use strict';
module.exports = (sequelize, DataTypes) => {
const Post = sequelize.define('Post', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: DataTypes.INTEGER
},
title: {
type: DataTypes.STRING,
allowNull: false,
},
content: {
type: DataTypes.TEXT,
allowNull: false,
},
publishedAt: {
type: DataTypes.DATE,
allowNull: true
},
}, {
classMethods: {
associate: function (models) {
Post.belongsTo(models.User, {
onDelete: 'CASCADE',
foreignKey: {
fieldName: 'authorId',
allowNull: false
}
});
}
}
});
return Post;
};
I repeted the same data between to file... I come from Laravel so maybe it's usual in the NodeJS world to do things like these.
To avoid code duplication between models and migrations, use models inside migrations as follows:
'use strict';
const { User } = require('../models');
module.exports = {
up: (queryInterface, Sequelize) => {
return User.sync();
// return queryInterface.createTable('user', { id: Sequelize.INTEGER });
},
down: (queryInterface, Sequelize) => {
return queryInterface.dropTable('user');
}
};
EDIT:
This is a good option for adding new tables only!
Caution for "{ alter: true }"! When changing existing columns, be aware that sequelize may not recognise a column rename and will perform two "DROP" and "ADD" operations instead of just one "CHANGE".
So, for updating schema, better use queryInterface.renameColumn
and queryInterface.changeColumn
or raw queries.
.sync()
queryInterface
raw queries
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With