I'm using Sequelize together with Node and JavaScript in one app. As you know when you execute sequelize-init
it creates config, migrations, models and seeders folder. Inside of the models folder, there is an index.js
file (generated by the cli), which is responsible for reading all of the models and their associations from the current folder:
index.js
'use strict';
const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const basename = path.basename(__filename);
const sequelize = require('../database/connection');
const db = {};
fs
.readdirSync(__dirname)
.filter(file => {
return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
})
.forEach(file => {
const model = require(path.join(__dirname, file))(sequelize, Sequelize.DataTypes);
db[model.name] = model;
});
Object.keys(db).forEach(modelName => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;
When I run my app, an error appears: TypeError: Class constructor model cannot be invoked without 'new' at line 17 which is the statement: var model = require(path.join(__dirname, file))(sequelize, Sequelize.DataTypes); Reading some of the posts related to this problem I found out that I need to install the @babel/preset-env
package along with @babel/cli, @babel/core, @babel/node
. I also created a .babelrc
file in the root directory, containing the following code:
.babelrc
{
"presets": [
[
"@babel/preset-env",
{
"targets": {
"esmodules": true
}
}
]
]
}
and updated my start
option of the scripts
tag inside package.json
to: "nodemon --exec babel-node app.js"
(I don't use webpack)
But when I run the app the error still appears. What do I miss or haven't set correctly?
const ThingThatIsAClass = require(path.join(__dirname, file)); const model = new ThingThatIsAClass(sequelize, Sequelize.DataTypes);
Don't try to cram so much on to a single line of code. It's hard to read, and makes it easy to miss trivial mistakes like this one.new (require(…))(…)
but that's even harder to understand.