代码之家  ›  专栏  ›  技术社区  ›  Marc Rasmussen

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

  •  0
  • Marc Rasmussen  · 技术社区  · 5 年前

    假设我有以下几点 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 回复  |  直到 5 年前
        1
  •  1
  •   Alen Genzić    5 年前

    使命感 require('./models/modelConfig');

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

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

    或者。直接返回sequelize即可:

    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();
    
        2
  •  1
  •   Atiq Ur Rehman    5 年前

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