当使用 Sequelize 创建模型时,开发人员可以在属性定义中使用 defaultValue
来设置默认值。本文介绍使用默认值的一些常见的场景:
字符串类型 (Sequelize.STRING
):
const User = sequelize.define('user', {
username: {
type: Sequelize.STRING,
defaultValue: 'DefaultUsername',
},
});
整数类型 (Sequelize.INTEGER
):
const Post = sequelize.define('post', {
likes: {
type: Sequelize.INTEGER,
defaultValue: 0,
},
});
布尔类型 (Sequelize.BOOLEAN
):
const Task = sequelize.define('task', {
completed: {
type: Sequelize.BOOLEAN,
defaultValue: false,
},
});
日期类型 (Sequelize.DATE
):
const Event = sequelize.define('event', {
eventDate: {
type: Sequelize.DATE,
defaultValue: Sequelize.NOW, // 当前日期和时间
},
});
UUID 类型 (Sequelize.UUID
):
const Product = sequelize.define('product', {
productId: {
type: Sequelize.UUID,
defaultValue: Sequelize.UUIDV4, // 生成 UUIDv4
},
});
使用函数作为默认值:
const Task = sequelize.define('task', {
description: {
type: Sequelize.STRING,
defaultValue: () => 'Default Description',
},
});
特殊默认值 - 当前日期和时间 (Sequelize.NOW
):
const LogEntry = sequelize.define('logEntry', {
logDate: {
type: Sequelize.DATE,
defaultValue: Sequelize.NOW,
},
});
实例
下面举一个史记中的例子说明,如何使用默认值将每条记录的主键(id)设置成随机的字符串。具体的做法为:使用 Sequelize 的 defaultValue 选项结合一个生成随机字符串的函数。
const Sequelize = require('sequelize');
const { v4: uuidv4 } = require('uuid'); // 使用 uuid 库生成随机字符串
const User = sequelize.define('user', {
id: {
type: Sequelize.STRING,
primaryKey: true,
defaultValue: () => uuidv4(), // 使用 uuidv4() 生成随机字符串
},
username: {
type: Sequelize.STRING,
allowNull: false,
},
// 其他属性...
});
// 示例:创建新用户
User.create({
username: 'exampleUser',
}).then((newUser) => {
console.log('New user created with id:', newUser.id);
});