1

I am new to node and here I am going to map mysql to my node project. model/User.js

const Sequelize = require('sequelize')
const db = require('../database/db.js')

module.exports = db.sequelize.define(
    'user',
    {
        user_id: {
            type: Sequelize.INTEGER,
            primaryKey: true,
            autoIncrement: true
        },
        first_name: {
            type: Sequelize.STRING
        },
        last_name: {
            type: Sequelize.STRING
        },
        email: {
            type: Sequelize.STRING
        },
        password: {
            type: Sequelize.STRING
        }
    },
    {
        timestamps: false
    }
);
    

In the above code module.exports = db.sequelize.define() an error comes as db.sequelize.define is not a function. What is the reason for this error in code?

database/db.js

const Sequelize = require("sequelize")
const db = {}
const sequelize = new Sequelize("node","root","",{
    host: "localhost",
    dialect: "mysql",
    operatorsAliases: false,

    pool: {
        max: 5,
        min: 0,
        acquire:30000,
        idle:10000
    }
})

db.sequelize = sequelize
db.sequelize = Sequelize

module.exports = db
Kamalka Fernando
  • 153
  • 1
  • 2
  • 13

2 Answers2

2

The problem that you have is in your database file db.js in the way you are defining and exporting sequelize. I recommend you to change it to this:

  const { Sequelize } = require('sequelize');
    const db = new Sequelize("node","root","",{
        host: "localhost",
        dialect: "mysql",
        operatorsAliases: false,
    
        pool: {
            max: 5,
            min: 0,
            acquire:30000,
            idle:10000
        }
    })
    
    // I deleted what was causing the problem

    module.exports = db;

And in model/User.js you should just call define() with db.define():

const Sequelize = require('sequelize')
const db = require('../database/db.js')

// I created an object here so you can export it
const User = db.define(
    'user',
    {
        user_id: {
            type: Sequelize.INTEGER,
            primaryKey: true,
            autoIncrement: true
        },
        first_name: {
            type: Sequelize.STRING
        },
        last_name: {
            type: Sequelize.STRING
        },
        email: {
            type: Sequelize.STRING
        },
        password: {
            type: Sequelize.STRING
        }
    },
    {
        timestamps: false
    }
);

module.exports = User;
Runsis
  • 831
  • 9
  • 19
1
db.sequelize = sequelize
db.sequelize = Sequelize

This is what makes you the problems. remove the 2nd line. or change it to:

db.Sequelize = Sequelize

And then dont use

const Sequelize = require('sequelize')

on your file, use db.Sequelize instead.

Talg123
  • 1,468
  • 1
  • 10
  • 15