node.js模块导出返回并使用对象

时间:2018-12-19 12:34:56

标签: javascript node.js

说我有以下modelConfiguration.js文件:

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;


};

现在在这里,您可以看到我返回了sequelize对象。

现在,我希望将一个变量设置为等于返回的对象,因此在我的server.js中,我将执行以下操作:

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

但是这不起作用。

有人可以告诉我我做错了什么吗? (也许我误会了一些东西)

2 个答案:

答案 0 :(得分:1)

调用require('./models/modelConfig');返回一个初始化Sequelize的函数。

您应该调用该方法以获取实例:

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

或者。只需直接返回续集即可:

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

答案 1 :(得分:1)

只需尝试添加它即可。它将给您返回一个对象而不是函数

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