Marc Rasmussen
Marc Rasmussen

Reputation: 20545

node.js module export return and use object

say i have the following modelConfiguration.js file:

const Sequelize = require('sequelize');
const dbConfig = require('../config/database.config');
module.exports = function () {

    const sequelize = new Sequelize(dbConfig.database, dbConfig.user, dbConfig.password, {
        host: 'localhost',
        dialect: 'mysql',

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

        // http://docs.sequelizejs.com/manual/tutorial/querying.html#operators
        operatorsAliases: false
    });


    const employee = sequelize.define('employee', {
        id:{
            type: Sequelize.DataTypes.INTEGER,
            primaryKey: true
        },
        token: Sequelize.DataTypes.TEXT
    });

    return sequelize;


};

Now here as you can see i return the sequelize object.

Now i wish to set a variable equal to the object returned so in my server.js i do the following:

const seq = require('./models/modelConfig');

However this does not work.

Can anyone tell me what ive done wrong? (Maybe ive misunderstood something)

Upvotes: 0

Views: 1384

Answers (2)

Atiq Ur Rehman
Atiq Ur Rehman

Reputation: 240

Just Try to add this.. It will give u back an object instead of function

const seq = require('./models/modelConfig')();

Upvotes: 1

Alen Genzić
Alen Genzić

Reputation: 1418

Calling require('./models/modelConfig'); returns a function that initializes Sequelize.

You should call the method to get an instance:

const seqInitializer = require('./models/modelConfig');
const seq = seqInitializer();

Alternatively. Just return sequelize directly:

const Sequelize = require('sequelize');
const dbConfig = require('../config/database.config');
function initSequelize() {

    const sequelize = new Sequelize(dbConfig.database, dbConfig.user, dbConfig.password, {
        host: 'localhost',
        dialect: 'mysql',

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

        // http://docs.sequelizejs.com/manual/tutorial/querying.html#operators
        operatorsAliases: false
    });


    const employee = sequelize.define('employee', {
        id:{
            type: Sequelize.DataTypes.INTEGER,
            primaryKey: true
        },
        token: Sequelize.DataTypes.TEXT
    });

    return sequelize;


};
module.exports = initSequelize();

Upvotes: 1

Related Questions