javascriptexpressserversequelize.js

Sequelize Model Not Creating Table in MySQL Database (TypeError: Cannot read properties of undefined (reading 'define'))


I’m working on a Node.js project using Sequelize with MySQL. The database connection is established successfully, and sequelize.sync({ alter: true }) runs without errors, but my users table is not being created.

Additionally, I’m getting the following error when requiring my model:

TypeError: Cannot read properties of undefined (reading 'define')
at Object.<anonymous> (B:\Builds\React-Express\nakargo\server\config\models\user.models.js:4:29)
at Module._compile (node:internal/modules/cjs/loader:1546:14)
at Object..js (node:internal/modules/cjs/loader:1689:10)
at Module.load (node:internal/modules/cjs/loader:1318:32)
at Function._load (node:internal/modules/cjs/loader:1128:12)
at TracingChannel.traceSync (node:diagnostics_channel:315:14)
at wrapModuleLoad (node:internal/modules/cjs/loader:218:24)
at Module.require (node:internal/modules/cjs/loader:1340:12)
at require (node:internal/modules/helpers:141:16)
at Object.<anonymous> (B:\Builds\React-Express\nakargo\server\config\db\dbConnection.js:24:19)

Here’s my setup:

user.models.js file

const { Sequelize, DataTypes } = require("sequelize");
const { sequelize } = require("../db/dbConnection");

const userModel = sequelize.define(
  "User",
  {
    id: {
      type: DataTypes.UUID,
      defaultValue: Sequelize.UUIDV4,
      primaryKey: true,
    },
    name: {
      type: DataTypes.STRING,
      allowNull: false,
    },
    email: {
      type: DataTypes.STRING,
      allowNull: false,
      unique: true,
      validate: {
        isEmail: true,
      },
    },
    password: {
      type: DataTypes.STRING,
      allowNull: false,
    },
  },
  {
    tableName: "users", // ✅ Explicit table name
    timestamps: true,
  }
);

module.exports = userModel; // ✅ Ensure model is exported correctly

db/dbConnection.js file

const { Sequelize } = require("sequelize");
const {
  DATABASE_NAME,
  DATABASE_USER,
  DATABASE_PASSWORD,
  DATABASE_HOST,
  DATABASE_PORT,
} = require("../envExports");

const sequelize = new Sequelize(
  DATABASE_NAME,
  DATABASE_USER,
  DATABASE_PASSWORD,
  {
    host: DATABASE_HOST,
    port: DATABASE_PORT,
    dialect: "mysql",
    logging: console.log, 
  }
);


const userModel = require("../models/user.models"); 

// Function to test database connection
const initializeDB = async () => {
  try {
    await sequelize.authenticate();
    console.log("✅ Database connection established successfully.");

    await sequelize.sync({ alter: true }); 
    console.log("✅ All models were synchronized successfully.");
  } catch (error) {
    console.error("❌ Failed to connect to the database:", error.message);
    process.exit(1); // Exit on critical failure
  }
};

// Function to clean up the connection
const disconnectDB = async () => {
  try {
    await sequelize.close();
    console.log("✅ Database connection closed successfully.");
  } catch (error) {
    console.error(
      "❌ Error while closing the database connection:",
      error.message
    );
  }
};

module.exports = { sequelize, initializeDB, disconnectDB, userModel }; 

Issue:

What I Have Tried:

Question:


Solution

  • This is a case where 2 or more modules depend on each other by sharing program elements. For example, a module A imports from B and at same time, B imports from A. We can summarise the dependency like so (A -> B -> A).

    The problem here, based on how module loading works is that Node.js while loading A will find B and while loading B, will discover B requires again module A. In other to avoid an infinite loop, Node.js will return an incompletely loaded module A in B which will result in undefined imports in module B.

    A quick fix would be:

    In practice this would be something like:

    user.models.js:

    const { Sequelize, DataTypes } = require("sequelize");
    
    const userModel = {
      name: "User",
      data: {
        id: {
          type: DataTypes.UUID,
          defaultValue: Sequelize.UUIDV4,
          primaryKey: true,
        },
        name: {
          type: DataTypes.STRING,
          allowNull: false,
        },
        email: {
          type: DataTypes.STRING,
          allowNull: false,
          unique: true,
          validate: {
            isEmail: true,
          },
        },
        password: {
          type: DataTypes.STRING,
          allowNull: false,
        },
      },
      {
        tableName: "users", // ✅ Explicit table name
        timestamps: true,
      }
    };
    
    module.exports = userModel; // ✅ Ensure model is exported correctly
    

    dbConnection.js:

    const { Sequelize } = require("sequelize");
    const {
      DATABASE_NAME,
      DATABASE_USER,
      DATABASE_PASSWORD,
      DATABASE_HOST,
      DATABASE_PORT,
    } = require("../envExports");
    
    const sequelize = new Sequelize(
      DATABASE_NAME,
      DATABASE_USER,
      DATABASE_PASSWORD,
      {
        host: DATABASE_HOST,
        port: DATABASE_PORT,
        dialect: "mysql",
        logging: console.log, 
      }
    );
    
    
    const userModel = require("../models/user.models"); 
    const userTable = sequelize.define(userModel.name, userModel.data);
    
    // Function to test database connection
    const initializeDB = async () => {
      try {
        await sequelize.authenticate();
        console.log("✅ Database connection established successfully.");
    
        await sequelize.sync({ alter: true }); 
        console.log("✅ All models were synchronized successfully.");
      } catch (error) {
        console.error("❌ Failed to connect to the database:", error.message);
        process.exit(1); // Exit on critical failure
      }
    };
    
    // Function to clean up the connection
    const disconnectDB = async () => {
      try {
        await sequelize.close();
        console.log("✅ Database connection closed successfully.");
      } catch (error) {
        console.error(
          "❌ Error while closing the database connection:",
          error.message
        );
      }
    };
    
    module.exports = { sequelize, initializeDB, disconnectDB, userTable };