0

I got a model folder which contains all sequelize schema models, and I tried to write an index.js in this model folder; but when I run the app, there is an error "sequelize is not defined" in the index.js. Please see my codes below.

"use strict";

const fs = require("fs");
const path = require("path");
const Sequelize = require("sequelize");
const basename = path.basename(module.filename);
const env = process.env.NODE_ENV || "development";
const config = require(__dirname + "/../config/config.json")[env];
const db = {};

if (config.use_env_variable) {
  const sequelize = new Sequelize(process.env[config.use_env_variable]);
} else {
  const sequelize = new Sequelize(config.database, config.username, config.password, config);
}


fs
  .readdirSync(__dirname)
  .filter((file) => {
    return (file.indexOf(".") !== 0) && (file !== basename) && (file.slice(-3) === ".js");
  })
  .forEach((file) => {
    const model = sequelize["import"](path.join(__dirname, file));
    db[model.name] = model;
  });

Object.keys(db).forEach((modelName) => {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
});

sequelize
          .authenticate()
          .then(() => {
            console.log("Connection has been established succesfully");
          })
          .catch((err) => {
            console.log("Unable to connect to the database:", err);
          })

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

db.group = require('./group')(sequelize, Sequelize);
db.service = require('./service')(sequelize, Sequelize);
db.store = require('./store')(sequelize, Sequelize);
db.appointment = require('./appointment')(sequelize, Sequelize);


module.exports = db;

4
  • you have declared 'sequelize' inside if block. That is why you are getting that error. Hope this will help you. Commented Dec 19, 2018 at 6:05
  • @R.Sarkar you should make that an answer Commented Dec 19, 2018 at 6:27
  • @SanSolo did that. It is a small change that is why i have posted that as comment. Commented Dec 19, 2018 at 6:52
  • @R.Sarkar, I suggested that so you could get points :) Commented Dec 19, 2018 at 7:27

1 Answer 1

2

you have declared 'sequelize' inside if block. That is why you are getting that error. Hope this will help you.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.