0

I'm having a problem while using Sequelize in a MVC project. Every time I try to use the hasOne or hasMany it brings me the same error. Some people had suggested to put every Models in a single file or creating a associations.js just to handle the associations. It works, but I personally don't think that's the best approach and I want to figure out a better alternative.

P.S: Using Postgre and Sequelize 6.28

Here is my code:

Models: Perfil.js

const { Sequelize, DataTypes } = require('sequelize')
const db = require('../../db/conn')

// MODELS
const User = require('./Usuario')

const Perfil = db.define('perfis', {
    id: {
        type: DataTypes.INTEGER,
        primaryKey: true,
        autoIncrement: true,
        allowNull: false
    },
    nome: DataTypes.STRING(90),
    descricao: DataTypes.TEXT('long')
}, { schema: "acesso", underscored: true })

Perfil.hasMany(User)

module.exports = Perfil

Usuarios.js

const { Sequelize, DataTypes } = require('sequelize')
const db = require('../../db/conn')

// MODELS
const Perfil = require('./Perfil')

const Usuario = db.define('usuarios', {
    id: {
        type: DataTypes.UUID,
        defaultValue: DataTypes.UUIDV4,
        primaryKey: true,
        allowNull: false
    },
    nome: {
        type: DataTypes.STRING(255),
        allowNull: false
    },
    nome_exibicao: DataTypes.STRING(50),
    sexo: DataTypes.STRING(45),
    email: {
        type: DataTypes.STRING(60),
        allowNull: false
    },
    password: {
        type: DataTypes.STRING(60),
        allowNull: false
    },
    status: {
        type: DataTypes.INTEGER,
        allowNull: false,
        defaultValue: 1
    }
}, { schema: "acesso", underscored: true });

Usuario.belongsTo(Perfil)

module.exports = Usuario
Luís
  • 3
  • 1

1 Answers1

0

You're trying to import models in each other's modules - these are circular dependencies. Please transform model registration code into functions in model modules and call them in one DB module registering associations only after all models will be registered. See this answer to get the idea how to do it properly.

Anatoly
  • 20,799
  • 3
  • 28
  • 42