Home:ALL Converter>Sequelize cyclic dependency

Sequelize cyclic dependency

Ask Time:2016-02-01T00:58:41         Author:andrepcg

Json Formatter

This is my User model

'use strict';
var bcrypt = require('bcrypt');

module.exports = function(sequelize, DataTypes) {
  var User = sequelize.define('User', {
    email: {
      type: DataTypes.STRING,
      validate: {
        isEmail: true,
        notEmpty: true,
        notNull: false
      },
      unique: true
    },

    password: DataTypes.STRING,
    name: DataTypes.STRING,

    username: {
      type: DataTypes.STRING,
      unique: true
    },

    admin: DataTypes.BOOLEAN,

    googleId: DataTypes.BOOLEAN

  }, {
    classMethods: {
      associate: function(models) {
        User.hasMany(models.Award);
        User.hasMany(models.Media);
        User.hasMany(models.Comment);
        User.hasMany(models.Like);
        User.hasMany(models.CheckIn);
      }
    }
  });


  return User;
};

and this is my Media model:

'use strict';

module.exports = function(sequelize, DataTypes) {
  var Media = sequelize.define('Media', {

    type: DataTypes.ENUM('photo', 'video'),
    description: DataTypes.STRING,

    url: DataTypes.STRING,

    gps: DataTypes.GEOMETRY('POINT')

  }, {
    classMethods: {
      associate: function(models) {
        //Media.belongsTo(models.Event);
        //Media.belongsTo(models.User);
        Media.hasMany(models.Comment);
        Media.hasMany(models.Like);
      }
    }
  });


  return Media;
};

And I'm getting this error:

Unhandled rejection Error: Cyclic dependency found. Users is dependent of itself.
Dependency chain: Awards -> Users -> Media => Users

Previously I had a cyclic dependency and it's now removed but sequelize still throws this error. Why is this happening?

If I remove the User.hasMany(models.Media) association the error will disappear. But why is it still happening when the Media model has no reference to the User model?

Author:andrepcg,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/35116541/sequelize-cyclic-dependency
ozgeneral :

Consider using hasMany as follows:\n\nUser.hasMany(models.Award, {as: 'ifYouWantAlias', constraints: false, allowNull:true, defaultValue:null});\n\n\nnote that you don't need the following part but it makes it clearer in my opinion.\n\nallowNull:true, defaultValue:null\n\n\nIt is explained well in here: http://docs.sequelizejs.com/en/latest/api/associations/",
2016-08-11T12:57:00
yy