sequelize: Getters not being called on find or get({plain: true}) neither

What are you doing?

I’ve got a model with a virtual method called payULink() that produces an URL using the id field of the model. On Sequelize 4.44.0, calling findAll() or get() on an instance calls the methods that produce this virtual property correctly, but on sequelize 5.8.5 it does not.

let purchaseOrder = sequelize.define('purchaseOrder', attributes, {
    getterMethods: {
        payULink() {
           return somethingMagic(this.id);
        }
    }
});

To Reproduce Steps to reproduce the behavior:

  1. Define a model with getters.
  2. Run findAll() on the model or get() on an instance.
  3. See error.

What do you expect to happen?

I was expecting to receive the object with the virtual properties obtained from calling the methods.

What is actually happening?

The object only contains the properties that are not virtual.

Environment

Dialect:

  • mysql
  • postgres
  • sqlite
  • mssql
  • any Dialect library version: mysql2 1.6.5 Database version: 5.7.18 Sequelize version: 5.8.5 Node Version: 10.15.3 OS: macOS Mojave If TypeScript related: TypeScript version: XXX Tested with latest release:
  • No
  • Yes, specify that version: 5.8.3

About this issue

  • Original URL
  • State: open
  • Created 5 years ago
  • Comments: 16 (6 by maintainers)

Most upvoted comments

They recommend making them virtual

sequelize.define('YerModel', {
   url:{
      type: DataTypes.VIRTUAL,
      get: ...getter function...
   }
});

But the breaking change/bug is that … if your query has an attributes array… the virtual field wont be returned unless specifically requested… see my comment above.

Its worth noting that after making them virtual fields - they will now also show up in the model instances list of fields (model.rawAttributes). i don’t know if you have any code that inspects the fields on your models… but I had to modify some of our rest api to account for the virtual fields showing up as a field. Mainly because our rest api allows you to sort a query if you pass it a valid field… and trying to sort by a virtual field blows up… (which might be another bug)

@papb we have > 50 models (with many getterMethods). This was not documented at all as a breaking change and I feel it should either be fixed or documented. I am curious why getterMethods are being deprecated? What is the best practice instead of them? I know you mentioned using VIRTUAL columns but how do you convert to them from something like this:

    getterMethods: {
      url: function() {
        if (this.cdn_base && this.cdn_id) {
          return `${this.cdn_base}/${this.cdn_id}/-/progressive/yes/`;
        } else {
          return this.legacy_url.indexOf('cdn.domain.com') > -1
            ? this.legacy_url.replace('.com/', '.com/compress/')
            : this.legacy_url;
        }
      },