I have the following file structure:
models/
  index.js
  something.js
  user.js
In index.js (this is generated by Sequalize and importing stuff from here works in other directories):
'use strict';
var fs        = require('fs');
var path      = require('path');
var Sequelize = require('sequelize');
var basename  = path.basename(module.filename);
var env       = process.env.NODE_ENV || 'development';
var config    = require(__dirname + '/../config/config')[env];
var db        = {};
if (config.use_env_variable) {
  var sequelize = new Sequelize(process.env[config.use_env_variable]);
} else {
  var sequelize = new Sequelize(config.database, config.username, config.password, config);
}
fs
  .readdirSync(__dirname)
  .filter(function(file) {
    return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
  })
  .forEach(function(file) {
    var model = sequelize['import'](path.join(__dirname, file));
    db[model.name] = model;
  });
Object.keys(db).forEach(function(modelName) {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db; // <<< I want to import that in something.js
user.js:
'use strict';
module.exports = (sequelize, DataTypes) => {
  const User = sequelize.define('User', {
    username: { type: DataTypes.STRING, allowNull: false, unique: true },
    password: { type: DataTypes.STRING, allowNull: false },
  }, {
    classMethods: {
      associate() {},
    },
  });
  return User;
};
something.js:
'use strict';
// this all logs an empty object
console.log(require('./index'));
console.log(require('.'));
console.log(require('./'));
console.log(require('../models'));
console.log(require('../models/'));
console.log(require('../models/index'));
module.exports = (sequelize, DataTypes) => {
  const Something = sequelize.define('Something', {
    name: DataTypes.STRING,
  }, {
    classMethods: {
      associate(models) {
      },
    },
  });
  return Something;
};
If I require db from files in other directories it works so I guess it's not a problem with exporting.
How can I require db in something.js so it's not undefined?
const neededStuff = require('./'); // the best
or:
const neededStuff = require('./index');
or:
const neededStuff = require('../models/');
                        Turns out it was a circular dependency. index.js was importing stuff from something.js and then I tried to import index.js in something.js. 
If module A requires('B') before it has finished setting up it's exports, and then module B requires('A'), it will get back an empty object instead what A may have intended to export.
http://selfcontained.us/2012/05/08/node-js-circular-dependencies/
But you can use methods from another model in sequelize with sequelize.models.Something.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With