mysql - Sequelize - 原始 :true and raw:false 和有什么区别

标签 mysql node.js express sequelize.js

根据doc

如果选项.raw

If set to true, field and virtual setters will be ignored

但是字段和虚拟 setter 的含义是什么?
我看过很多网站,但似乎没有关于当 options.raw 的值为 true/false 时查询结果格式的示例。

假设我在 Sequelize 中创建了 users 模型

const Sequelize = require('sequelize');
const DataTypes = Sequelize.DataTypes;
const db = require('../sequelize')

let users = db.define('users', {
    id: {
      type: DataTypes.UUID,
      defaultValue: DataTypes.UUIDV4,
      allowNull: false,
      primaryKey: true
    },
    email: {
        type: DataTypes.STRING,
        allowNull: false,
        unique: 'email'
    },
    password: {
      type: DataTypes.STRING,
    },
  },
  {
    hooks: {
      beforeCount(options) {
        options.raw = true;  // what would be the difference when I set it to false
      }
    }
  }
);
  
users.sync().then(() => {
console.log('user table created');
});

module.exports = users;

当我将 options.raw 设置为 false 时会有什么不同?
有什么例子吗?

最佳答案

Doc

In its most basic form set will update a value stored in the underlying dataValues object. However, if a custom setter function is defined for the key, that function will be called instead. To bypass the setter, you can pass raw: true in the options object.

如果 raw 为 true,自定义 getter 和 setter 将被忽略。

require('sqlite3');
const { Sequelize, DataTypes } = require('sequelize');

const sequelize = new Sequelize('sqlite::memory:')

const User = sequelize.define('User', {
  firstName: {
    type: DataTypes.STRING,
    get() {
        return this.getDataValue('firstName').toUpperCase()
    }
  },
  lastName: {
    type: DataTypes.STRING,
    set(value) {
        this.setDataValue('lastName', value + '--------');
    }
  }
});

let user = User.build({ firstName: 'John', lastName: 'Doe' });
console.log(user.lastName); // Doe--------
console.log(user.get()) // {firstName: "JOHN", id: null, lastName: "Doe--------"}

user = User.build({ firstName: 'John', lastName: 'Doe' }, {raw: true});
console.log(user.lastName); // Doe
console.log(user.get({raw: true})) // {firstName: "John", id: null, lastName: "Doe"}

关于mysql - Sequelize - 原始 :true and raw:false 和有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67530074/

相关文章:

node.js - 将 Passport 使用从 Mongoose 转换为 Sequelize

node.js - Express - req.ip 返回 127.0.0.1

php - htmlspecialchars utf-8 返回空字符串

java - 始终使用 jhipster 将日期保存到数据库中的今天日期

mysql - 具有事件记录的mysql中的SET数据类型

javascript - node.js 文件中绑定(bind)的函数是什么

mysql - mysql根据另外两个表中的值将数据插入表中

node.js - Web 聊天中的 Azure 测试 : HTTP status code NotFound

javascript - POST 返回值到 MongoDB onsubmit

node.js - 将 redis 与 node.js (express) 一起使用