Class constructor model cannot be invoked without new sequelize
A common error in Sequelize!
The error "Class constructor Model cannot be invoked without 'new'" typically occurs when you're trying to create a new instance of a Sequelize model without using the new
keyword.
Here's what's happening:
In JavaScript, when you define a class (like a Sequelize model), it's not automatically instantiated when you create an instance of it. Instead, you need to use the new
keyword to create a new instance.
For example, if you have a Sequelize model defined like this:
const { Model, DataTypes } = require('sequelize');
const sequelize = new Sequelize('database', 'username', 'password', {
host: 'localhost',
dialect: 'mysql',
});
class User extends Model {}
User.init({
name: {
type: DataTypes.STRING,
},
email: {
type: DataTypes.STRING,
},
}, {
sequelize,
modelName: 'User',
});
You can't create a new instance of the User
model like this:
const user = User();
This will throw the error "Class constructor Model cannot be invoked without 'new'".
Instead, you need to use the new
keyword to create a new instance:
const user = new User();
This will create a new instance of the User
model, and you can then use it to interact with your database.
So, to fix the error, simply add the new
keyword when creating an instance of your Sequelize model.