我目前正在我的 MySQL 数据库上运行 Sequelize.js 代码,该数据库是使用迁移创建的。我有一个包含人员的表,其定义如下:
return queryInterface.createTable('Persons', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
unique: true,
type: Sequelize.INTEGER
},
email: {
allowNull: false,
unique: true,
type: Sequelize.STRING
},
firstName: {
type: Sequelize.STRING
},
lastName: {
type: Sequelize.STRING
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
结果表如下所示:
`Persons` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`email` varchar(255) NOT NULL,
`firstName` varchar(255) DEFAULT NULL,
`lastName` varchar(255) DEFAULT NULL,
`createdAt` datetime NOT NULL,
`updatedAt` datetime NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id` (`id`),
UNIQUE KEY `email` (`email`)
)
当我使用 Model.create({}) (括号之间没有任何内容)向数据库添加条目时,以下对象将添加到数据库中:
id email firstName lastName createdAt updatedAt
1 '' NULL NULL 2019-05-21 15:33:13 2019-05-21 15:33:13
数据库中的每个 NOT NULL 列都会获得一个默认值(对于 varchar 为空字符串,对于 bool 值为 false,对于日期时间为 NOW())。
The Sequelize.js docs陈述以下内容:
setting allowNull to false will add NOT NULL to the column, which means an error will be thrown from the DB when the query is executed if the column is null. If you want to check that a value is not null before querying the DB, look at the validations section below.
title: { type: Sequelize.STRING, allowNull: false },
我想收到官方文档中所述的错误,但不知道我做错了什么。
最佳答案
我解决了这个问题。
我必须将allowNull 添加到模型定义中。这在第一次尝试时出现了一些声明问题,但是现在重新审视该问题后,它起作用了,并且我得到了正确的错误。
module.exports = (sequelize, DataTypes) => {
const Persons = sequelize.define('Persons', {
email: {
type: DataTypes.STRING(100),
allowNull: false
},
firstName: DataTypes.STRING(40),
lastName: DataTypes.STRING(40)
}, {});
return Persons;
};
关于mysql - Sequelize 自动为 NOT NULL 列设置默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56241834/