question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Associations - Automatic methods not working

See original GitHub issue

I’m new to Node.js, Express and Sequelize (v5.8.6). In my project, I have defined a hasMany-belongsTo relationship. Location is the source model and User is the target model. After having defined the association, I am supposed to have access to the magic methods (getUsers(), setUsers(), etc.). But when I try to Location.getUsers(), I get the error:

TypeError: Location.getUsers is not a function

I’ve used Sequelize-CLI to generate my models and migrations. My files look like this:

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 || 'production';
const config = require(__dirname + '/../config/config.js')[env];
const db = {};

var 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 = sequelize['import'](path.join(__dirname, file));
    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;

models/location.js

'use strict';
module.exports = (sequelize, DataTypes) => {
  const Location = sequelize.define('Location', {
    name: {
      allowNull: false,
      type: DataTypes.STRING
    },
  }, {
    sequelize,
    modelName: 'location',
    underscored: true,
  });

  Location.associate = function(models) {
    Location.hasMany(models.User);
  };

  return Location;
};

models/user.js

'use strict';
module.exports = (sequelize, DataTypes) => {
  const User = sequelize.define('User', {
    email: {
      allowNull: false,
      type: DataTypes.STRING
    },
    location_id: {
      type: DataTypes.INTEGER
    },
  }, {
    sequelize,
    modelName: 'user',
    underscored: true
  });
  User.associate = function(models) {
    User.belongsTo(models.Location);
  };
  return User;
};

When I try doing console.log(Location.associations) from my location.js file, I just get {} but when I try to log it in my index.js file, I get {Users: Users} but I still can’t access Location.getUsers()

Any help would be appreciated. Thanks in advance!

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Reactions:1
  • Comments:7 (1 by maintainers)

github_iconTop GitHub Comments

1reaction
ccemeraldeyescommented, Sep 6, 2019

nah, in my case the method was just named wrong lol You’re probably right that that was @ashishsanjayrao 's issue though

0reactions
Pedro-99commented, Jun 27, 2022

guys, I have the same issue, how did you solve that?

in my case, I was adding “_” in the model’s name and that causes to this error, just pay attention to your model’s name

Read more comments on GitHub >

github_iconTop Results From Across the Web

Sequelizejs: no auto-generation of methods from associations
I am trying to setup a m:n association using feathersjs with sequelize. I am following this 'instruction', but have to adjust to updates ......
Read more >
Active Record Associations - Ruby on Rails Guides
Active Record supports automatic identification for most associations with standard names. However, Active Record will not automatically identify bi-directional ...
Read more >
Associations - Sequelize
These three calls will cause Sequelize to automatically add foreign keys to the appropriate models (unless they are already present).
Read more >
Troubleshooting Windows device enrollment errors in Intune
Solution: Use one of the following methods to address this issue: Disable MDM automatic enrollment in Azure. Sign in to the Azure portal....
Read more >
FAQs - Harvard Implicit Association Test
What can I do about an automatic preference that I would rather not have? ... about the role of implicit associations in mental...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found