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.