question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

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

See original GitHub issue

I can’t define model using extends from Model abstract class

I using babel@7, webpack, and sequelize@5. anything is ok when I using sequelize.define(...) but when i using with extends it not working with my road.

my model users.js

export class Users extends Model {
  static init(sequelize) {
    return super.init({
      id: {
        type: DataTypes.STRING(36),
        primaryKey: true,
        unique: true,
        allowNull: false,
        defaultValue: () => uuidv4(), // uuid@3.3.2
        validate: {
          isUUID: 36
        }
      },
      username: {
        type: DataTypes.STRING(36),
        unique: true,
        allowNull: false
      },
      password: {
        type: DataTypes.STRING,
        allowNull: false
      },
      firstname: {
        type: DataTypes.STRING(100),
        allowNull: false
      },
      lastname: {
        type: DataTypes.STRING(100),
        allowNull: false
      },
      role: {
        type: DataTypes.STRING(10),
        allowNull: true
      },
      createdDate: {
        type: DataTypes.DATE,
        defaultValue: () => DateUtil.getUTCDateTime()
      },
      isDeleted: {
        type: DataTypes.INTEGER(1),
        defaultValue: 0
      }
    },
    {
      tableName: 'users',
      modelName: 'users',
      ...baseOptions, // my options, that's ok.
      sequelize
    });
  }

  static associate(models) {
    return this.associations = {
      playlists: Users.hasMany(models['playlists'])
    };
  }
}

my intance Database file database.js

export class Database {
  constructor() {
    Database.instance.authenticate()
    .then(() => {
      Object.values(models).map(model => {
        return model.init(Database.instance);
      }).filter(model => {
        return (typeof model.associate).includes('function');
      }).forEach(model => {
        model.associate(Database.instance.models);
      });
      Database.instance.sync().then(() => {
     /**
        i can't create this record with models
        I changed `Database.instance.models.users` to Users from extends class
        but it's not working so. 
      */
        Database.instance.models.users.create({
          "username": "anc123",
          "password": "anc123",
          "firstname": "anc",
          "lastname": "nguyen"
        }).then(() => {
          console.log('ok');
        }).catch(err => {
          console.error(err);
        });
        console.log('Initialize database has been established successfully.');
      });
    })
    .catch((error) => {
      console.error('Unable to initialize to the database:', error);
    });
  }

  static get instance() {
    if(!Database._instance) {
      Database._instance = new Sequelize(DB_CONFIG);
    }
    return Database._instance;
  }
}

in my main

...
import { Database } from '../'
new Database();

Error:

Unhandled rejection TypeError: Class constructor Model cannot be invoked without 'new'
    at new users (C:\Users\Hydrogener\Desktop\noquere\soul\src\models\users.js:32:19)
    at Function.build (C:\Users\Hydrogener\Desktop\noquere\soul\node_modules\sequelize\lib\model.js:2141:12)
    at Function.create (C:\Users\Hydrogener\Desktop\noquere\soul\node_modules\sequelize\lib\model.js:2194:17)
    at Function.create (C:\Users\Hydrogener\Desktop\noquere\soul\src\models/users.js:65:5)
    at create (C:\Users\Hydrogener\Desktop\noquere\soul\src\helpers/database.js:17:40)
    at tryCatcher (C:\Users\Hydrogener\Desktop\noquere\soul\node_modules\bluebird\js\release\util.js:16:23)
    at Promise._settlePromiseFromHandler (C:\Users\Hydrogener\Desktop\noquere\soul\node_modules\bluebird\js\release\promise.js:512:31)
    at Promise._settlePromise (C:\Users\Hydrogener\Desktop\noquere\soul\node_modules\bluebird\js\release\promise.js:569:18)
    at Promise._settlePromise0 (C:\Users\Hydrogener\Desktop\noquere\soul\node_modules\bluebird\js\release\promise.js:614:10)
    at Promise._settlePromises (C:\Users\Hydrogener\Desktop\noquere\soul\node_modules\bluebird\js\release\promise.js:694:18)
    at _drainQueueStep (C:\Users\Hydrogener\Desktop\noquere\soul\node_modules\bluebird\js\release\async.js:138:12)
    at _drainQueue (C:\Users\Hydrogener\Desktop\noquere\soul\node_modules\bluebird\js\release\async.js:131:9)
    at Async._drainQueues (C:\Users\Hydrogener\Desktop\noquere\soul\node_modules\bluebird\js\release\async.js:147:5)
    at Immediate.Async.drainQueues [as _onImmediate] (C:\Users\Hydrogener\Desktop\noquere\soul\node_modules\bluebird\js\release\async.js:17:14)
    at runCallback (timers.js:705:18)
    at tryOnImmediate (timers.js:676:5)
    at processImmediate (timers.js:658:5)

Dialect: mysql Dialect version: ??? Database version: 5.7 Sequelize version: 5.6.0 Tested with latest release: No (If yes, specify that version)

Note : I had use @babel/plugin-transform-classes and @babel/plugin-proposal-class-properties for babel plugin.

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:7 (2 by maintainers)

github_iconTop GitHub Comments

12reactions
nviethuancommented, Apr 19, 2019

Thanks you so much. I fixed it, just remove @babel/plugin-transform-classes pluggin and add

{
  "presets": [
    ["env", {
      "targets": {
        "node": "current"
      }
    }]
  ]
}
8reactions
harrytran103commented, May 17, 2020

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.

Read more comments on GitHub >

github_iconTop Results From Across the Web

TypeError: Class constructor model cannot be invoked without ...
It turns out that an ES6-class transpiled by babel can't extend a real ES6 class (The Sequelize.Model ES6-class for example).
Read more >
Class constructor Model cannot be invoked without 'new' and ...
Hi all, I using v4 to defined my model as: @Options({ sequelize, ... Unhandled rejection TypeError: Class constructor Model cannot be ...
Read more >
Class constructor Sequelize cannot be invoked without 'new'
Class constructor Sequelize cannot be invoked without 'new'. Returning the following error when trying to extract the Op property from db.
Read more >
Javascript ES6 TypeError Class constructor Client cannot be ...
When I try to execute nodemon command I always see this error TypeError: Class constructor Client cannot be invoked without 'new'.
Read more >
TypeError: Class constructor VueCustomElement cannot be invoked ...
“TypeError: Class constructor VueCustomElement cannot be invoked without 'new'” Code Answer · TypeError: Class constructor Model cannot be invoked without.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found