Home > Blockchain >  Importing sequelize model says that it is undefined
Importing sequelize model says that it is undefined

Time:12-19

OBS. Excuse my code, my project is like a playground I set it up only to study. Sequelize is connecting to the database by calling authenticate but my models are "undefined", so sad...

I will show one image to show my project structure.

enter image description here

my index and product files are like this:

index:

'use strict';

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

let sequelize;
if (config.use_env_variable) {
  sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
  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 = require(path.join(__dirname, file))(sequelize, Sequelize.DataTypes);
    db[model.name] = model;
  });

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

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

module.exports = db;

produto model

'use strict';
const {
  Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
  class produto extends Model {
    /**
     * Helper method for defining associations.
     * This method is not a part of Sequelize lifecycle.
     * The `models/index` file will call this method automatically.
     */
    static associate(models) {
      // define association here
    }
  };
  produto.init({
    id: { type: DataTypes.NUMBER, 
       primaryKey: true},
    titulo: DataTypes.STRING,
    preco: DataTypes.NUMBER
  }, {
    sequelize,
    modelName: 'produto',
  });
  return produto;
};

CodePudding user response:

You can try this :

const Produto = require("../models/produto");

CodePudding user response:

It's produto lowercase, half a day on this...

  const produto = require('../modelos');

because it's the name of the module that counts... or something like that.

  • Related