简体   繁体   中英

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)

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();

只需尝试添加它。它会给你一个对象而不是函数

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM