Sequelize Error: you must use the 'as' keyword to specify the alias of the association you want to include. - node.js

Viewed 6736

I am making a web application which is similar to 'Twitter'.

When I ran the server,

'user is associated to user multiple times. To identify the correct association, You must use the 'as' keyword to specify the alias of the association you want to include.' <- this message appeared.

I applied 'as' keyword for the relationship between 'followers' and 'followings'. but the error message kept on appearing.

I'm sure that I did something wrong in someway, but I can't figure out what exactly it is. can somebody help me?

  1. models/index.js

    '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;
db.User = require('./user')(sequelize, Sequelize);
db.Post = require('./post')(sequelize, Sequelize);
db.Hashtag = require('./hashtag')(sequelize, Sequelize);

db.User.hasMany(db.Post); //1 : n
db.Post.belongsTo(db.User); 
// m: n
db.Post.belongsToMany(db.Hashtag, { through: 'PostHashtag' });
db.Hashtag.belongsToMany(db.Post, { through: 'PostHashtag' });

// I use alias here *****
db.User.belongsToMany(db.User, {
  foreignKey: 'followingId',
  as: 'Followers',
  through: 'Follow',
});

db.User.belongsToMany(db.User, {
  foreignKey: 'followerId',
  as: 'Followings',
  through: 'Follow',
});

module.exports = db; 

  1. models/user.js
    module.exports = (sequelize, DataTypes) => (
  sequelize.define('user', {
    email: {
      type: DataTypes.STRING(40),
      allowNull: true,
      unique: true,
    },
    nick: {
      type: DataTypes.STRING(15),
      allowNull: false,
    },
    password: {
      type: DataTypes.STRING(100),
      allowNull: true,
    },
    provider: {
      type: DataTypes.STRING(10),
      allowNull: false,
      defaultValue: 'local',
    },
    snsId: {
      type: DataTypes.STRING(30),
      allowNull: true,
    },
  }, {
    timestamps: true,
    paranoid: true,
  })
);


  1. models/post.js
module.exports = (sequelize, DataTypes) => (
  sequelize.define('user', {
    email: {
      type: DataTypes.STRING(40),
      allowNull: true,
      unique: true,
    },
    nick: {
      type: DataTypes.STRING(15),
      allowNull: false,
    },
    password: {
      type: DataTypes.STRING(100),
      allowNull: true,
    },
    provider: {
      type: DataTypes.STRING(10),
      allowNull: false,
      defaultValue: 'local',
    },
    snsId: {
      type: DataTypes.STRING(30),
      allowNull: true,
    },
  }, {
    timestamps: true,
    paranoid: true,
  })
);

  1. models/hashtag.js

module.exports = (sequelize, DataTypes) => (
    sequelize.define('hashtag', {
        title: {
            type: DataTypes.STRING(15),
            allowNull: false,
            unique: true,
        },
    }, {
        timestamps: true,
        paranoid: true,
    })
); 
1 Answers

I think this will solve your problem you have to create a table follower than associate it with user table with following and follower alias and use it to query follower and following

follower Model

module.exports =   (sequelize, datatypes) => {
     sequelize.define('follower', {
        _id: {
            type: datatypes.integer,
            allownull: false,
            primarykey: true,
            autoincrement: true
        },
        userid: {
            type: datatypes.integer,
            allownull: false
        },
        followingid: {
            type: datatypes.integer,
            allownull: false
        }
    });
} 

association

db.follower.belongsTo(db.user, {
    as: 'following',
    foreignkey: 'followingid'
});

db.follower.belongsto(db.user, {
    as: 'follower',
    foreignkey: 'userid'
});

query to get follower

follower.findall({
    where: {
        followingid: userid
    },
    attributes: ['_id'],
    include: [{
        model: user, attributes:
            ['fullname', 'username', '_id', 'picture'],
        as: 'follower'
    }]
})
Related