Sequelize is a promise-based Node. js ORM for Postgres, MySQL, MariaDB, SQLite and Microsoft SQL Server. We often use this with node , express etc , while using sequelize with express and mysql we get an common error called TypeError: require(...) is not a function

Error Log

............/models/index.js:24
const model = require(path.join(__dirname, file))(sequelize, Sequelize.DataTypes);

                                                     ^
TypeError: require(...) is not a function
    at fs.readdirSync.filter.forEach.file (/home/shihab_munna/VsCode/testapp/models/index.js:24:54)
    at Array.forEach (<anonymous>)
    at Object.<anonymous> (/home/shihab_munna/VsCode/testapp/models/index.js:23:4)
    at Module._compile (internal/modules/cjs/loader.js:778:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Module.require (internal/modules/cjs/loader.js:692:17)
    at require (internal/modules/cjs/helpers.js:25:18)

here we can see the error is happening because of const model = require(path.join(__dirname, file))(sequelize, Sequelize.DataTypes); this line .

In this line what happens is this require(path.join(__dirname, file)) looks for a model in the models directory, so if you declare a empty file in models that time this error occurs. Because it's looking for a model function to import but it's not getting a function.

Solution

Basically there is two way to handle this error :

  • Delete That empty file from models directory.

or

  • Use a if-else condition to avoid this line to be executed when it's not getting a function.

edit into your :models/index.js replace this code with code from here (left of your screen):

    .forEach(file => {
    const model = require(path.join(__dirname, file))(sequelize,  Sequelize.DataTypes);;
    db[model.name] = model;
  });

This one worked absolutely fine for me:

[nodemon] 2.0.4
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node app.js`
App Running on http://localhost/3000
Executing (default): SELECT 1+1 AS result
Succcessfully Connected to the database

if you are in same type of problem it can help you to.

If it fails to solve your share with me(with your error log) in the comment bellow