sequelize icon indicating copy to clipboard operation
sequelize copied to clipboard

Class constructor Model cannot be invoked without 'new' and how getter v4 work?

Open zon999 opened this issue 9 years ago • 30 comments

Hi all, I using v4 to defined my model as:

@Options({
    sequelize,
    tableName: 'V2_category',
    timestamps: false
})
@Attributes({
    id: {
        type: DataTypes.INTEGER,
        allowNull: false,
        primaryKey: true,
        autoIncrement: true
    },
    name: DataTypes.STRING,
    name_vi: DataTypes.STRING,
    code: DataTypes.STRING,
    type: DataTypes.STRING,
    created_at: DataTypes.DATE,
    updated_at: DataTypes.DATE,
})
export class V2Category extends Model {
    get fullName() {
        return this.name + '-' + this.name_vi;
    }

    set fullName(fullName) {
        const names = fullName.split(' ');
        this.name = names.pop();
        this.name_vi = names.join(' ');
    }
}

and i import in others: import {V2Category as category} from '../models/V2_category';

my query : findCategoryById (id) { return category.findOne({ where: { 'id': id } }); }

When run i got an error:

Unhandled rejection TypeError: Class constructor Model cannot be invoked without 'new'

However, i add { where: { 'id': id }, raw: true } my code working but i can't use getter function fullName. Could you tell me where my mistake and how to fix it? Thanks

zon999 avatar Jun 25 '17 08:06 zon999

Please post the whole stack trace

felixfbecker avatar Jun 26 '17 10:06 felixfbecker

I had the same problem

During debugging I found out that the Model constructor returns a class instead of a function

I have a suspicion that the problem arises at the moment of inheritance

kalyuk avatar Jun 29 '17 07:06 kalyuk

In JavaScript, a class is a function.

felixfbecker avatar Jun 29 '17 08:06 felixfbecker

@felixfbecker nice joke, I'm very familiar with JS I could not understand why he inherited this error when he inherited But if you go the old way and use define, the error disappears static build(values, options) { if (Array.isArray(values)){ return this.bulkBuild(values, options); } return new this(values, options); }`

kalyuk avatar Jun 29 '17 09:06 kalyuk

I have the same problem.

HriBB avatar Jul 05 '17 03:07 HriBB

I think it has something to do with the way babel transpiles the code. After I changed my .babelrc file to this:

{
  "presets": [
    ["env", {
      "targets": {
        "node": "current"
      }
    }]
  ]
}

it works as expected.

HriBB avatar Jul 16 '17 02:07 HriBB

Yes, that is very likely. @zonorion could you post the transpiled JS of that model?

felixfbecker avatar Jul 16 '17 08:07 felixfbecker

Intypescript case, my solution was to change target from es5 to es6

{
  "compilerOptions": {
    "target": "es6", // <=
    // ...
  }
}

SuperPaintman avatar Jul 22 '17 21:07 SuperPaintman

I'm getting this as well. Just upgraded from 3 to 4.4.2, and when I change my model definitions to:

const attributes = {/*...*/};
const options = {
  sequelize,
};
class User extends Sequelize.Model {
  someInstanceMethod() {}
}
User.someStaticMethod = () => {};
User.init(attributes, options);

I started seeing the error anytime Sequelize attempted to create an instance of User (such as User.findOne()).

My .babelrc:

{
  "presets": ["es2015", "react", "stage-0"]
}

Switching to this for now:

const User = sequelize.define('User', attributes, options);
User.prototype.someInstanceMethod = function() {}; // function can't be () => {}
User.someClassMethod = () => {};

tybro0103 avatar Jul 23 '17 01:07 tybro0103

@juhaelee says:

You just need to use the env preset package instead of es2015

  "presets": [
    ["env", {
      "targets": {
        "node": "current"
      }
      }],
    "stage-1"
  ],
  "plugins": []
}

cinic avatar Aug 17 '17 21:08 cinic

Sr, i missed any notifications I used: { "presets": [ "es2015-node6", "stage-3" ], "plugins": [ ["transform-decorators-legacy"], [ "transform-runtime", { "polyfill": false, "regenerator": true } ], [ "istanbul", { "exclude": [ "test/*.js" ] } ] ] }

sequelize woking fine!

zon999 avatar Sep 14 '17 05:09 zon999

It turns out that an ES6-class transpiled by babel can't extend a real ES6 class (The Sequelize.Model ES6-class for example).

So class MyEntity extends Sequelize.Model { ... } won't work if MyEntity is transpiled into ES5.

See https://stackoverflow.com/questions/36577683/babel-error-class-constructor-foo-cannot-be-invoked-without-new

The solution i used, was to use es2015-node5 instead of es2015. But ONLY on the server, of course, not on the client - i.e. not when transpiling for the browser. So i didn't put this in my .babelrc, but added it to the "build-server" command-line scripts in package.json instead: babel .... --no-babelrc --presets=es2015-node5,stage-0,react.

BjarkeNL avatar Sep 14 '17 16:09 BjarkeNL

have almost the same problem how do i solve it ... looking for a solution

kipchubett avatar Oct 30 '18 07:10 kipchubett

@corneliouzbett

have almost the same problem how do i solve it ... looking for a solution

do you found solution ?

kalyuk avatar Nov 02 '18 18:11 kalyuk

I'm getting this error as well when using some of the example code listed within Express / Sequelize setup. Seems the the offending line of code is within the cli's default generated models/index.js

const model = sequelize['import'](path.join(__dirname, file))

Altered things with babel and so forth, but haven't gotten it working just yet.

christopher4lis avatar Feb 07 '19 18:02 christopher4lis

Turns out in my case, I had a previously created model in the models folder that was causing things to break:

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

const Post = db.define('post', {
    title: Sequelize.STRING(255),
    body: Sequelize.TEXT('long'),
    excerpt: Sequelize.STRING(500),
    tags: Sequelize.STRING(500),
    slug: Sequelize.STRING(255),
    thumbnail_path: Sequelize.STRING(255),
    hero_path: Sequelize.STRING(255),
    updatedAt: Sequelize.DATE
})

module.exports = Post

This was preventing the file from being read correctly by sequelize and causing the error listed in this thread. Advice for others: Make sure all of your code inside of your models folder is valid and from examples.

christopher4lis avatar Feb 07 '19 18:02 christopher4lis

For those running into this, this is a bug in babel. I haven't been able to solve it on my end using the suggested solutions likely because I use babel runtime transformations. There is a PR open @babel to resolve this. Hopefully it will be merged soon. https://github.com/babel/babel/pull/8656

mschipperheyn avatar Feb 10 '19 15:02 mschipperheyn

Mine got solved via:

{
  "presets": [
    [
      "@babel/preset-env",
      {
        "targets": {
          "node": true
        }
      }
    ]
  ]
}

cpkenn09y avatar Mar 10 '19 06:03 cpkenn09y

Im not using a transpiler and i have this error as well

jcfinnerup avatar Apr 17 '19 14:04 jcfinnerup

Same issue here and my .babelrc is:

{
  "presets": [
    [
      "@babel/preset-env",
      {
        "targets": {
          "node": "current"
        }
      }
    ]
  ]
}

Any other suggestions to solve this?

TidyIQ avatar Apr 27 '19 14:04 TidyIQ