Martin
Martin

Reputation: 58

Sequelize and module.exports

I am new to nodejs and Sequelize and have been having an issue that I cannot figure out how to get over. I want to use a connection I created and exported it to a module.

Like this:

const dotEnv        = require('dotenv');
const Sequelize     = require('sequelize');

dotEnv.config();

module.exports.connection = async () => {
    try{
        const sequelize = new Sequelize(process.env.DB_DATABASE, process.env.DB_USER, process.env.DB_PASSWORD, {
            host: process.env.DB_HOST,
            port: process.env.DB_PORT,
            dialect: 'mysql',
            logging: false,
            define: {
                charset: 'utf8',
                collate: 'utf8_general_ci',
            },
        });
        await sequelize
        .authenticate()
        .then(() => {
            console.log('Connection has been established successfully.');
        })
        .catch(error => {
            throw error;
        });
    }catch(error){
        throw error;
    }
}

I then have another file where I want to use it that looks like this

const Sequelize     = require('sequelize');
const { connection }= require('../database');

const accountModel = connection.define('accounts', {
  // attributes
  id: {
      type: Sequelize.UUID,
      defaultValue: Sequelize.UUIDV4,
      primaryKey: true
  },
  name: {
    type: Sequelize.STRING,
    allowNull: false
  },
  email: {
      type: Sequelize.STRING,
      unique: true
  },
  password: {
      type: Sequelize.STRING,
      allowNull: false,
      //is: /^[0-9a-f]{64}$/i
  },
  permission: {
      type: Sequelize.STRING,
      allowNull: false
  },
  discount: {
      type: Sequelize.INTEGER,
      allowNull: false
  }
}, {
  freezeTableName: true
});
module.exports = connection.model('accounts', accountModel);

The problem is that I get told that: TypeError: connection.define is not a function,

The connection works, the database is running, everything else works And last if I do it like this, it works too:

const dotEnv        = require('dotenv');
const Sequelize     = require('sequelize');

dotEnv.config();

const sequelize = new Sequelize(process.env.DB_DATABASE, process.env.DB_USER, process.env.DB_PASSWORD, {
    host: process.env.DB_HOST,
    port: process.env.DB_PORT,
    dialect: 'mysql',
    logging: false,
    define: {
        charset: 'utf8',
        collate: 'utf8_general_ci',
    },
});

const accountModel = sequelize.define('accounts', {
  // attributes
  id: {
      type: Sequelize.UUID,
      defaultValue: Sequelize.UUIDV4,
      primaryKey: true
  },
  name: {
    type: Sequelize.STRING,
    allowNull: false
  },
  email: {
      type: Sequelize.STRING,
      unique: true
  },
  password: {
      type: Sequelize.STRING,
      allowNull: false,
      //is: /^[0-9a-f]{64}$/i
  },
  permission: {
      type: Sequelize.STRING,
      allowNull: false
  },
  discount: {
      type: Sequelize.INTEGER,
      allowNull: false
  }
}, {
  freezeTableName: true
});
module.exports = sequelize.model('accounts', accountModel);

I am really not sure why the module one does not work but the direct method does. I have tried to search Google and Stack Overflow for a solution.

Upvotes: 3

Views: 4391

Answers (2)

tchibu
tchibu

Reputation: 56

The problem in your first approach is that you exported first of all an async function and not the Sequelize instance (as it is in your second example) and secondly the function itself is not returning anything. That's why there is no connection.define() function when you require that in another file.

try this in database.js and it should work:

module.exports.connection = new Sequelize(process.env.DB_DATABASE, process.env.DB_USER, process.env.DB_PASSWORD, {
            host: process.env.DB_HOST,
            port: process.env.DB_PORT,
            dialect: 'mysql',
            logging: false,
            define: {
                charset: 'utf8',
                collate: 'utf8_general_ci',
            },
        });

You can do all that authenticate() and try {} catch (error) {} somewhere else for example in your very first js file where you starting the server by requiring the same database.js file. But for the model definitions it's important that you are exporting just the new Sequelize() instance to them to be able to use define()

Upvotes: 1

Aleksandar Zoric
Aleksandar Zoric

Reputation: 1483

I would do something like this. In the connections file you export the function then in the accountModel file you import and invoke the function.

connection.js:

exports.connection= async function() { // Stuff here }

accountModel.js:

const { connection }= require('../database');
let connection = await connection.connection();

Upvotes: 0

Related Questions