node-sequelize学习笔记五(获取器, 设置器 & 虚拟字段)
获取器
const User = sequelize.define('user', { // 假设我们想要以大写形式查看每个用户名, // 即使它们在数据库本身中不一定是大写的 username: { type: DataTypes.STRING, get() { const rawValue = this.getDataValue('username'); return rawValue ? rawValue.toUpperCase() : null; } } }); const user = User.build({ username: 'SuperUser123' }); console.log(user.username); // 'SUPERUSER123' console.log(user.getDataValue('username')); // 'SuperUser123'
设置器
const User = sequelize.define('user', { username: DataTypes.STRING, password: { type: DataTypes.STRING, set(value) { // 在数据库中以明文形式存储密码是很糟糕的. // 使用适当的哈希函数来加密哈希值更好. this.setDataValue('password', hash(value)); } } }); const user = User.build({ username: 'someone', password: 'NotSo§tr0ngP4$SW0RD!' }); console.log(user.password); // '7cfc84b8ea898bb72462e78b4643cfccd77e9f05678ec2ce78754147ba947acc' console.log(user.getDataValue('password')); // '7cfc84b8ea898bb72462e78b4643cfccd77e9f05678ec2ce78754147ba947acc'
如果我们想将模型实例中的另一个字段包含在计算中,那也是可以的,而且非常容易!
const User = sequelize.define('user', { username: DataTypes.STRING, password: { type: DataTypes.STRING, set(value) { // 在数据库中以明文形式存储密码是很糟糕的. // 使用适当的哈希函数来加密哈希值更好. // 使用用户名作为盐更好. this.setDataValue('password', hash(this.username + value)); } } });
虚拟字段
const { DataTypes } = require("sequelize"); const User = sequelize.define('user', { firstName: DataTypes.TEXT, lastName: DataTypes.TEXT, fullName: { type: DataTypes.VIRTUAL, get() { return `${this.firstName} ${this.lastName}`; }, set(value) { throw new Error('不要尝试设置 `fullName` 的值!'); } } });