sequelize: Class constructor Model cannot be invoked without 'new'

Hello!

What are you doing?

const sequelize = new Sequelize(
  process.env.DATABASE_URL,
  {
    dialect: "postgres",
    logging: false,
  }
)

class Account extends Model {
  id!: number
  name!: string
}

Account.init(
  {
      name: {
        type: new DataTypes.STRING(128),
        allowNull: false,
      }
  },
  {
      tableName: "Account",
      sequelize,
    }
)

const acc = await Account.create({
    name: "Roland Leth",
})

To Reproduce Steps to reproduce the behavior:

  1. Define model Account with class approach. sequelize.define works properly.
  2. Try and create/update an entry. Read/delete queries work.
  3. See the error and stack trace attached.

What do you expect to happen?

The record to be created/updated.

What is actually happening?

It throws Class constructor Model cannot be invoked without 'new'.

Environment

Dialect:

  • mysql
  • postgres
  • sqlite
  • mssql
  • any Dialect library version: 7.12 Database version: 11 Sequelize version: 5.12.2 Node Version: 12.6 OS: 10.15 If TypeScript related: TypeScript version: 3.6.0-dev.20190801 (3.5.x behaves the same) Tested with latest release:
  • No
  • Yes, specify that version: 5.12.2

I’ve read all that I could find about this error, including other issues here, but my lack of web experience might be at fault.

I’m using razzle, if that helps in any way.

This is my .babelrc:

{
  "presets": [
    "razzle/babel", // NEEDED
    [
      "@babel/preset-env",
      {
        // "spec": true,
        // "debug": true,
        "useBuiltIns": "usage",
        "corejs": "3.1.4"
      }
    ]
  ]
}

And this is razzle’s.

Stack trace

path-to-project/build/server.js:6985
    return _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_1___default()(this, _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_2___default()(Account).apply(this, arguments));
                                                                                                                                                                                               ^

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

  6983 |     _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, Account);
  6984 | 
> 6985 |     return _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_1___default()(this, _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_2___default()(Account).apply(this, arguments));
  6986 |   }
  6987 | 
  6988 |   return Account;

    at new Account (path-to-project/build/server.js:6985:192)
    at Function.build (path-to-project/node_modules/sequelize/lib/model.js:2164:12)
    at Function.create (path-to-project/node_modules/sequelize/lib/model.js:2217:17)
    at Module../src/server.ts (path-to-project/src/server.ts:7:1)
    at __webpack_require__ (path-to-project/build/webpack:/webpack/bootstrap:685:1)
    at fn (path-to-project/build/webpack:/webpack/bootstrap:59:1)
    at Module../src/index.ts (path-to-project/build/webpack:/src/index.ts:1:1)
    at __webpack_require__ (path-to-project/build/webpack:/webpack/bootstrap:685:1)
    at fn (path-to-project/build/webpack:/webpack/bootstrap:59:1)
    at Object.0 (path-to-project/build/server.js:8034:18)
    at __webpack_require__ (path-to-project/build/webpack:/webpack/bootstrap:685:1)
    at path-to-project/build/webpack:/webpack/bootstrap:752:1
    at Object.<anonymous> (path-to-project/build/server.js:757:10)
    at Module._compile (internal/modules/cjs/loader.js:776:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
    at Module.load (internal/modules/cjs/loader.js:643:32)
    at Function.Module._load (internal/modules/cjs/loader.js:556:12)
    at Function.Module.runMain (internal/modules/cjs/loader.js:839:10)
    at internal/main/run_main_module.js:17:11

Please let me know what other info I can provide.

Thank you!

About this issue

  • Original URL
  • State: closed
  • Created 5 years ago
  • Reactions: 3
  • Comments: 20 (12 by maintainers)

Commits related to this issue

Most upvoted comments

@SimonSchick Interesting. I didn’t know that. Indeed, adding the following tsconfig.json to my root folder fixed it:

// tsconfig.json
{
    "compilerOptions": {
        "target": "es6"
    }
}

Output:

Executing (default): CREATE TABLE IF NOT EXISTS `AccountTests` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `name` VARCHAR(128), `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL);
Executing (default): PRAGMA INDEX_LIST(`AccountTests`)
Executing (default): INSERT INTO `AccountTests` (`id`,`name`,`createdAt`,`updatedAt`) VALUES (NULL,$1,$2,$3);

Thanks 👍

ts-node uses es5 as a transpilation target, which is probably the issue here, you need to specify at least es6, but again this isn’t a sequelize issues, you need to create an environment which is at least equivalent to node v6+ for sequelize v5.

Hi guys, I have the same issue with tsc (TypeScript compiler).

version

{
  "sequelize": "^5.21.6",
  "ts-node": "^8.10.1",
  "typescript": "^3.7.2"
}

model

import { Model, DataTypes } from 'sequelize';
import sequelize from './';
import { OrderStatus } from '../components/constants';

class Order extends Model {
  public id!: number;
  public total!: number;
  public finalTotal!: number;
  public status: OrderStatus;
  public start_date: Date;
  public end_date: Date;
  public created_at: Date;
  public updated_at: Date;
}

Order.init({
  id: {
    type: DataTypes.UUID,
    primaryKey: true,
    defaultValue: DataTypes.UUIDV4
  },
  total: {
    type: DataTypes.INTEGER,
    allowNull: true,
  },
  finalTotal: {
    type: DataTypes.INTEGER,
    allowNull: true,
    validate: {
      len: {
        args: [2, 5],
        msg: 'Name must be from 2 to 5 characters in length'
      },
    }
  },
  status: {
    type: DataTypes.ENUM(OrderStatus.InProcess, OrderStatus.Done)
  },
}, {
  sequelize,
  tableName: 'orders',
})

export default Order;

sequelize.import

const modelsPath = `${__dirname}/../src/models`;
  const models = fs
    .readdirSync(modelsPath)
    .filter((filename: string) => /model.ts$/.test(filename))
    .reduce((total: any, filename: string) => {
      const model = sequelize.import(path.join(modelsPath, filename));
      total[capitalize(model.name)] = model;
      return total;
    }, {});

  // Sets up the associations for each model.
  Object.keys(models).forEach((modelName: string) => {
    if ('associate' in models[modelName]) {
      models[modelName].associate(models);
    }
  });

error

TypeError: Class constructor Order cannot be invoked without 'new'
      at Sequelize.import (node_modules/sequelize/lib/sequelize.js:486:38)
      at /home/cuongw/Workspace/SaveMoney/service-template/test/utils.ts:18:37
      at Array.reduce (<anonymous>)
      at Object.exports.prepareModels (test/utils.ts:17:6)
      at Object.exports.loadFixtures (test/utils.ts:35:18)
      at Context.<anonymous> (test/order.test.ts:16:11)
      at processImmediate (internal/timers.js:456:21)

Please tell me a solution. Thank all.

Again I’m not exactly an expert when it comes to babel, but can you tell me why you need babel on node 12.6? Since it seems you want to use types I’d strongly recommend using the typescript compiler instead.

I was able to reproduce. Micro SSCCE/MCVE/reprex:

// test.ts
const Sequelize = require("sequelize");
const sequelize = new Sequelize('sqlite::memory:');

class AccountTest extends Sequelize.Model {
    id!: number
    name!: string
}
AccountTest.init({ name: Sequelize.STRING(128) }, { sequelize });

(async () => {
    await sequelize.sync();
    await AccountTest.create({ name: "Foo" });
})();

Executing ts-node test.ts:

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

Both luckily (because I solved it) and sadly (because I don’t have a solution for this problem), I used @SimonSchick’s suggestion to stop using Babel and moved to TS’ compiler. Everything is working properly now.

If I’ll ever need Babel and have to fix this, I’ll be sure to come back and update this as well.

@rolandleth When you do, add a link on your question to this issue, and also post a link of the question here, so that others in a similar situation can find help faster. Thanks!

Yupp, will do that since it still persists and it’s clearly out of scope.

Thank you both for your help and input, have a great weekend!

Hey, @SimonSchick, what should I do now? It’s a duplicate, but of an issue that is closed and whose solution didn’t help me — I already tried it before opening this one 😞