sequelize - what is the difference between raw:true and raw:false

Viewed 1077

According to doc

if options.raw

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

But what is the meaning of field and virtual setters?
I have watched lots of sites but seem no examples for the format of query result when the value of options.raw is true/false.

Let say I have users model created in Sequelize

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;

What would be the difference when I set options.raw to false?
Any examples for it?

1 Answers

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.

If raw is true, custom getters and setters will be ignored.

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"}
Related