Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize: TypeError: Cannot read property '_modelAttribute' of undefined

I am trying to order by the count of the associated model, and have been getting the following error from Sequelize

Cannot read property '_modelAttribute' of undefined

I have following code:

db.user.belongsToMany(db.user, {
  as: "User",
  through: "UserFollowers",
  foreignKey: "user_id"
});
db.user.belongsToMany(db.user, {
  as: "Follower",
  through: "UserFollowers",
  foreignKey: "follower_id"
});

and

   User.findAll({
          attributes:["username",db.sequelize.literal('(SELECT COUNT(*) FROM "public"."Users","public"."UserFollowers" WHERE "Users".user_id = "UserFollowers".user_id GROUP BY "Users".user_id)'),'followercount'],
          include:[{model:User,as:'Follower'}],
          order:[{ model: User, as: 'Follower' }[db.sequelize.literal('followercount')],'DESC']
      }).then(users => {
          res.json(users)
      })

I appreciate any help!

like image 661
TripleN Avatar asked Nov 17 '25 04:11

TripleN


1 Answers

From glancing at the code, the issue seems to be on the ordering clause. Change it to:

order: [[{ model: User, as: 'Follower' }, 'followercount', 'DESC']]

If that doesn't cut it, try logging the outcome of the query by adding logging: console.log. That should help you identify what part is failing by analyzing the sql query.

like image 105
André Holstein Avatar answered Nov 19 '25 21:11

André Holstein