使用module.exports在函数内导出变量以在另一个文件中引用

时间:2020-02-28 16:00:38

标签: ecmascript-6 sequelize.js

我正在努力寻找解决方案,但是无论我对ES6解构和全局变量有多少了解,我仍然无法解决。

因此,我正在使用sequelize处理我的MySQL数据库,它一直运行良好,直到我修改了database.js文件并在其中实现了“ postgres”,因为我想添加(如果不存在则创建数据库。 。)语法添加到我的database.js中,因为事实证明,它并不是那么简单,并且易于使用续集。现在,主要的问题是,在修改了database.js文件之后,我不再能够引用/提取“ sequelize”变量,因为它现在的作用域位于另一个函数内部的函数内部。我只需要找到一种方法来提取此变量并对其进行解构,以便我可以将它与module.exports一起发送,并可以在其他users.js文件(具有我的用户数据库模型)中使用它。

这是我的 database.js 文件(我的所有数据库配置都在这里)

const Sequelize = require('sequelize');
const pg = require('pg');

   function initialize(callback) {
    var dbName = 'onlinemarket',
        username = 'root',
        password = 'root',
        host = '127.0.0.1'
 
    var sequelize= ''; // in order to make it a global variable
    var conStringPri = 'postgres://' + username + ':' + password + '@' + host + '/postgres';
    var conStringPost = 'postgres://' + username + ':' + password + '@' + host + '/' + dbName;

    // connect to postgres db
    pg.connect(conStringPri, function(err, client, done) { 
        // create the db and ignore any errors, for example if it already exists.
        client.query('CREATE DATABASE IF NOT EXISTS onlinemarket', function (err) {
              if (err) throw err;
              client.query('USE onlinemarket', function (err) {
                  if (err) throw err;
                          client.query('CREATE TABLE IF NOT EXISTS users('
                          + 'ID INT NOT NULL AUTO_INCREMENT,'
                          + 'username VARCHAR(255) NOT NULL,'
                          + 'password VARCHAR(255) NOT NULL,'
                          + 'first_name VARCHAR(255),'
                          + 'last_name VARCHAR(255),'
                          + 'PRIMARY KEY(ID),'
                          +  ');', function (err) {
                              if (err) throw err;
                          client.query('CREATE TABLE IF NOT EXISTS posts('
                          + 'ID INT NOT NULL AUTO_INCREMENT,'
                          + 'title VARCHAR(255) NOT NULL,'
                          + 'description VARCHAR(255) NOT NULL,'
                          + 'category VARCHAR(255) NOT NULL,'
                          + 'city VARCHAR(255) NOT NULL,'
                          + 'country VARCHAR(255) NOT NULL,'
                          + 'images VARCHAR(255) NOT NULL,'
                          + 'price DECIMAL(10,2) NOT NULL,'
                          + 'postDate DATE NOT NULL,'
                          + 'deliveryType VARCHAR(255) NOT NULL,'
                          + 'sellerName VARCHAR(255) NOT NULL,'
                          + 'mobile VARCHAR(255) NOT NULL,'
                          + 'PRIMARY KEY(ID),'
                          +  ');', function (err) {
                              if (err) throw err;
                      });
                  });
              });
            });
          }, function(err) {
            //db should exist now, initializing Sequelize after that
            sequelize = new Sequelize(conStringPost); //this is the variable which i need to get

            callback(sequelize);
            client.end(); // close the connection

            sequelize.authenticate().then(() => {
              console.log('Database connection has been established successfully.');
            }).catch(err => {
              console.error('Unable to connect to the database: ' + err);
            });
    });
}

module.exports =  { sequelize };

这是我创建用户模型的users.js文件,正如您在文件顶部看到的那样,该文件试图导入/要求使用解构的“ sequelize”变量以获取“ sequelize.define()”加工。只要我没有正确提取并导出sequelize变量,控制台就会一直提示“未定义sequelize”

这是我的 users.js 文件

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

//The app needs to understand "sequelize.define"
module.exports = sequelize.define(
    'users',
    {
        ID: {
            type: Sequelize.INTEGER,
            primaryKey: true,
            autoIncrement: true
        },
        username: {
            type: Sequelize.STRING
        },
        password: {
            type: Sequelize.STRING
        },
        first_name: {
            type: Sequelize.STRING
        },
        last_name: {
            type: Sequelize.STRING
        }
    }, {
        timestamps: false
    }
);

在我对其进行修改之前(由于添加了“ postgres”),它是完美的。 这是我修改前的旧 database.js 文件,当时我仅使用sequelize,它顺利导出了变量,以便在 users.js 文件中引用。

const Sequelize = require('sequelize');
const db = {} 

const sequelize = new Sequelize("onlinemarket", "root", "root", {
    host: "127.0.0.1",
    dialect: "mysql"
})

sequelize.authenticate()
  .then(() => {
    console.log('Database connection has been established successfully.');
  })
  .catch(err => {
    console.error('Unable to connect to the database: ' + err);
  });


  db.sequelize = sequelize;
  db.Sequelize = sequelize; 

  module.exports = db;

0 个答案:

没有答案