Skip to content

Cannot read property 'name' of undefined when associating with hasMany #11691

Closed

Description

@mfgabriel92

Issue Description

I have User and Message models, and I am attempting to associate them. User is supposed to have many Message and Message belongs to User. What's happening is that hasMany is throwing some errors I cannot figure out why, and what's more maddening is that I had already used a few months ago the way things are now, but this time it decided to not work.

StackOverflow / Slack attempts

https://stackoverflow.com/questions/58934011/sequelize-typeerror-cannot-read-property-name-of-undefined-between-a-1-rel

Additional context

User migration and class:

module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.createTable('users', {
      id: {
        type: Sequelize.INTEGER,
        autoIncrement: true,
        primaryKey: true,
        allowNull: false
      },
      username: {
        type: Sequelize.STRING,
        unique: true,
        allowNull: false
      },
      first_name: {
        type: Sequelize.STRING,
        allowNull: false
      },
      middle_name: {
        type: Sequelize.STRING
      },
      last_name: {
        type: Sequelize.STRING,
        allowNull: false
      },
      created_at: {
        type: Sequelize.DATE,
        allowNull: false
      },
      updated_at: {
        type: Sequelize.DATE,
        allowNull: false
      }
    })
  },

  down: queryInterface => {
    return queryInterface.dropTable('users')
  }
}
import Sequelize, { Model } from 'sequelize'

class User extends Model {
  static init(sequelize) {
    super.init(
      {
        username: Sequelize.STRING,
        first_name: Sequelize.STRING,
        middle_name: Sequelize.STRING,
        last_name: Sequelize.STRING
      },
      {
        sequelize
      }
    )

    return this
  }

  static associate(models) {
    this.hasMany(models.Message)
  }

  static async findByUsername(username) {
    return User.findOne({ where: { username } })
  }
}

export default User

Message migration and model:

module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.createTable('messages', {
      id: {
        type: Sequelize.INTEGER,
        autoIncrement: true,
        primaryKey: true,
        allowNull: false
      },
      user_id: {
        type: Sequelize.INTEGER,
        references: { model: 'users', key: 'id' },
        onUpdate: 'CASCADE',
        onDelete: 'CASCADE',
        allowNull: false
      },
      content: {
        type: Sequelize.STRING,
        allowNull: false
      },
      created_at: {
        type: Sequelize.DATE,
        allowNull: false
      },
      updated_at: {
        type: Sequelize.DATE,
        allowNull: false
      }
    })
  },

  down: queryInterface => {
    return queryInterface.dropTable('messages')
  }
}
import Sequelize, { Model } from 'sequelize'

class Message extends Model {
  static init(sequelize) {
    super.init(
      {
        user_id: Sequelize.INTEGER,
        content: Sequelize.STRING
      },
      {
        sequelize
      }
    )

    return this
  }

  static associate(models) {
    this.belongsTo(models.User, { foreignKey: 'user_id' })
  }
}

export default Message

Database class where things get initialized:

import Sequelize from 'sequelize'
import config from '../config/database'
import models from '../models'

class Database {
  constructor() {
    this.init()
  }

  init() {
    this.connection = new Sequelize(config)

    Object.keys(models).forEach(model => {
      models[model].init(this.connection)

      if ('associate' in models[model]) {
        models[model].associate(models)
      }
    })
  }
}

export default new Database()

models.js file where the models are imported and exported (GraphQL context):

import User from './User'
import Message from './Message'

export default {
  User,
  Message
}

Error when starting the server with npm start:

this.as = this.target.options.name.plural;
                                    ^

TypeError: Cannot read property 'name' of undefined
    at new HasMany (/home/gabriel/Workspace/apollo-server-sample/node_modules/sequelize/lib/associations/has-many.js:51:37)
    at Function.hasMany (/home/gabriel/Workspace/apollo-server-sample/node_modules/sequelize/lib/associations/mixin.js:34:25)
    at Function.associate (/home/gabriel/Workspace/apollo-server-sample/src/models/User.js:21:10)
    at forEach (/home/gabriel/Workspace/apollo-server-sample/src/database/index.js:17:23)
    at Array.forEach (<anonymous>)
    at Database.init (/home/gabriel/Workspace/apollo-server-sample/src/database/index.js:13:25)
    at new Database (/home/gabriel/Workspace/apollo-server-sample/src/database/index.js:7:10)
    at Object.<anonymous> (/home/gabriel/Workspace/apollo-server-sample/src/database/index.js:23:16)
    at Module._compile (internal/modules/cjs/loader.js:956:30)
    at Module._compile (/home/gabriel/Workspace/apollo-server-sample/node_modules/pirates/lib/index.js:99:24)
    at Module._extensions..js (internal/modules/cjs/loader.js:973:10)
    at Object.newLoader [as .js] (/home/gabriel/Workspace/apollo-server-sample/node_modules/pirates/lib/index.js:104:7)
    at Module.load (internal/modules/cjs/loader.js:812:32)
    at Function.Module._load (internal/modules/cjs/loader.js:724:14)
    at Module.require (internal/modules/cjs/loader.js:849:19)
    at require (internal/modules/cjs/helpers.js:74:18)
    at Object.<anonymous> (/home/gabriel/Workspace/apollo-server-sample/src/app.js:7:1)
    at Module._compile (internal/modules/cjs/loader.js:956:30)
    at Module._compile (/home/gabriel/Workspace/apollo-server-sample/node_modules/pirates/lib/index.js:99:24)
    at Module._extensions..js (internal/modules/cjs/loader.js:973:10)
    at Object.newLoader [as .js] (/home/gabriel/Workspace/apollo-server-sample/node_modules/pirates/lib/index.js:104:7)
    at Module.load (internal/modules/cjs/loader.js:812:32)
[nodemon] app crashed - waiting for file changes before starting...

Issue Template Checklist

Is this issue dialect-specific?

  • No. This issue is relevant to Sequelize as a whole.
  • Yes. This issue only applies to the following dialect(s): XXX, YYY, ZZZ
  • I don't know.

Would you be willing to resolve this issue by submitting a Pull Request?

  • Yes, I have the time and I know how to start.
  • Yes, I have the time but I don't know how to start, I would need guidance.
  • No, I don't have the time, although I believe I could do it if I had the time...
  • No, I don't have the time and I wouldn't even know how to start.

Activity

  1. silveiratalita commented on Dec 16, 2019

    @silveiratalita

    I have the same problem the message is node_modules/sequelize/lib/associations/has-one.js:31
    this.as = this.target.options.name.singular;
    ^
    TypeError: Cannot read property 'name' of undefined

    I have no idea what to do, i tried a lot of different things, but nothing works in this case.
    If i found the error ill come back here to say how fix!

  2. reopened this on Jan 16, 2020
  3. papb commented on Jan 16, 2020

    @papb
    Member

    @mfgabriel92 Did you find out what was happening?

  4. added
    status: awaiting response
    and removed
    status: awaiting response
    on Jan 16, 2020
  5. bobspace commented on Jan 16, 2020

    @bobspace

    I'm having the same issue with a very similarly constructed project.

  6. papb commented on Jan 16, 2020

    @papb
    Member

    @bobspace Can you please construct a sequelize-sscce?

  7. added
    status: awaiting response
    and removed on Jan 16, 2020
  8. bobspace commented on Jan 16, 2020

    @bobspace

    I can but I'm worried that this won't produce a representative example. Like the sample code above, I'm creating my models via ES6 classes, and not sequelize.define().

    This is relevant because the error I'm getting is:

     /Users/bobspace/GitHub/myProject/node_modules/sequelize/lib/associations/has-one.js:31
    12:19:23 PM web.1 |        this.as = this.target.options.name.singular;
    12:19:23 PM web.1 |                                      ^
    12:19:23 PM web.1 |  TypeError: Cannot read property 'name' of undefined
    

    If I add console.log(this) on the line above has-one.js:31, it outputs undefined, even though that line is running inside of the HasOne class's constructor. I suspect this is some kind of structural/scoping issue.

    Any ideas/suggestions based on that?

  9. papb commented on Jan 16, 2020

    @papb
    Member

    @bobspace Thanks, I don't understand why you think your example won't be representative... The fact that you're using ES6 classes instead of sequelize.define does not matter, since things should work just fine if you're using ES6 classes as well :)

    My suggestion is really to see a sequelize-sscce before anything else haha

  10. bobspace commented on Jan 16, 2020

    @bobspace

    Et voila: sequelize/sequelize-sscce#36

    Builds successfully on my local machine and passed your CI. (FWIW I am not using sequelize.sync() to sync my DB; I'm using migrations instead.

    Here's what my migration looks like just in case:

    module.exports = {
      up: (queryInterface, Sequelize) => {
        return queryInterface.addColumn(
          'Locations',
          'userId',
          {
            type: Sequelize.INTEGER,
            references: {
              model: 'Users',
              key: 'id',
            },
            onUpdate: 'CASCADE',
            onDelete: 'SET NULL',
          },
        );
      },
    
      down: (queryInterface, Sequelize) => {
        return queryInterface.removeColumn(
          'Locations',
          'userId',
        );
      },
    };
    

    Now what? 😅

  11. bobspace commented on Jan 16, 2020

    @bobspace

    (Thanks for your help, btw 🙏)

  12. papb commented on Jan 16, 2020

    @papb
    Member

    Now what? 😅

    Good question... Since everything is green in the sequelize-sscce you made, this means the attempt to reproduce the problem was not successful, right? Am I missing something?

  13. bobspace commented on Jan 16, 2020

    @bobspace

    Under the use case provided by the SSCCE, yes.

    Now I have to figure out how my usage differs from this bare bones case, and if the root cause is misuse on my part, or a valid use case that is not tested by your reproduction test harness.

  14. bobspace commented on Jan 16, 2020

    @bobspace

    @papb How could I run a migration in the SSCCE?

  15. bobspace commented on Jan 16, 2020

    @bobspace

    FIGURED IT OUT

    @mfgabriel92 and I had the same flaw in our database initialization code.

    Object.keys(models).forEach(model => {
      models[model].init(this.connection)
    
      if ('associate' in models[model]) {
        models[model].associate(models)
       }
     })
    

    If one of the dependent models has not been init-ed, then any calls to association methods will fail. You can fix this with one loop to call init() and another to call associate, i.e.

    Object.keys(models).forEach(model => {
      models[model].init(this.connection)
     })
    
    Object.keys(models).forEach(model => {
      if ('associate' in models[model]) {
        models[model].associate(models)
      }
    })
    

    Confirmed the failure in the SSCCE by writing in a similar structure. Thanks @papb for helping me troubleshoot.

  16. bobspace commented on Jan 16, 2020

    @bobspace

    (@silveiratalita See if this fixes your issue as well.)

  17. silveiratalita commented on Jan 17, 2020

    @silveiratalita

    @bobspace really sorry for the delay in answering you! Yesterday was a very busy day!

    I solved my problem, i remember that the problema was about relationship between tables. I was trying to use 'has many' to 'has many'. I thought that, if i have, for example, a lot meetups, in these meetups could has a lot of players, but the same players could be invited to differents meetups! But I was wrong! I solved the problem changing these relation ship to

    MeetupPlayer.hasOne(Player, { foreignKey: 'id' });
    MeetupPlayer.hasOne(Meetup, { foreignKey: 'id' });

    Only cause the meetup has the player and the player are inside the meetup, only once. i can be inside another meetup, but only one time, cause Im just one player.

    Thanks for your answer!!!!=]

  18. papb commented on Jan 17, 2020

    @papb
    Member

    Hi @bobspace, happy to hear you figured it out.

    @papb How could I run a migration in the SSCCE?

    Just call sequelize.queryInterface.whatever in the same way you would do in a migration.

  19. removed
    status: awaiting response
    on Jan 17, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions