sequelize / sequelize

Feature-rich ORM for modern Node.js and TypeScript, it supports PostgreSQL (with JSON and JSONB support), MySQL, MariaDB, SQLite, MS SQL Server, Snowflake, Oracle DB (v6), DB2 and DB2 for IBM i.
https://sequelize.org/
MIT License
29.52k stars 4.27k forks source link

ES6 class setters and getters do not work for field in schema #9300

Open mikefowler opened 6 years ago

mikefowler commented 6 years ago

What are you doing?

Attempting to use a custom setter on my model class.

The Sequelize release notes for 4.x, under "New Features", reads: "You can then define custom methods, class methods and getters/setter directly in the class".

Defining the get/set methods in the field's schema definition works as expected, but I expect the following to work as well.

// Foo.js

import Sequelize, { Model } from 'sequelize';

class Foo extends Model {
  get languages() {
    console.log('Getting languages…');
    return JSON.parse(this.getDataValue('languages'));
  }

  set languages(value) {
    console.log('Setting languages to', value);
    this.setDataValue('languages', JSON.stringify(value));
  }
}

const SCHEMA = {
  languages: Sequelize.TEXT,
};

export default (sequelize) => {
  Foo.init(SCHEMA, { sequelize });
}

// index.js

foo.update({
  languages: ['en', 'es'],
});

What do you expect to happen?

What is actually happening?

Dialect: mysql (but irrelevant, because the error is thrown before reaching the adapter) Dialect version: n/a Database version: n/a Sequelize version: 4.22.0 Tested with latest release: No

Note : Your issue may be ignored OR closed by maintainers if it's not tested against latest version OR does not follow issue template.

heisian commented 6 years ago

I think there's an error in your code:

  set languages(value) {
    console.log('Setting languages to', value);

    // this.setDataValue(JSON.stringify(value)); <-- MISSING KEY TO SET

    this.setDataValue('languages', JSON.stringify(value));
  }

http://docs.sequelizejs.com/class/lib/model.js~Model.html#instance-method-setDataValue

@mickhansen

mikefowler commented 6 years ago

@heisian yes, that seems to be a typo (which I've now corrected in my psuedocode), but the issue is that the setters and getters are not being called, period. In a simple test, those console.log statements are never run.

jamesbrucepower commented 6 years ago

I currently have exactly the same issue, after spending much time debugging models.js source I gave up and added VIRTUAL attributes with getters and setters

sushantdhiman commented 6 years ago

Looks like we are still using options.getterMethods / options.setterMethods, I thought we remove support for that with v4.

Tagged as bug

0x62 commented 5 years ago

Any update on this?

toymachiner62 commented 1 year ago

My setter does not seem to be called either using sequelize 6