javascriptsequelize.jsfeathers-sequelize

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 feathersjs has gone throught in the meantime.

My hook to associate an already created user with an already created item:

module.exports = function (options = {}) { 
  return function (hook) {
    hook.app.service('users')
      .get(hook.data[0].user_id)
      .then(users => {
        hook.app.service('items')
          .find(hook.data[0].item_id)
          .then(benches => items.addMyusers(users));
      });

    return Promise.resolve(hook);
  };
};

I get:

error: Unhandled Rejection at: Promise  Promise {
  <rejected> TypeError: Cannot read property 'addMyusers' of undefined

Under my user model definition I set the asssocation with:

  users.associate = function (models) {
    users.belongsToMany(models.items, {
      through: {
        model: 'favorites-items',
        unique: false
      },
      foreignKey: 'item_id',
      as: 'myitems',
      constraints: false
    });
  };

under item model definition:

  items.associate = function (models) { 
    items.belongsToMany(models.users, {
      through: {
        model: 'favorites-items',
        unique: false
      },
      as: 'myusers',
      foreignKey: 'user_id',
      constraints: false
    });
  };

Why does addMyusers not exist? Methods like these should be auto-generated when making the association?

As stated in the sequelize docs:

This will add methods getUsers, setUsers, addUser,addUsers to Project, and getProjects, setProjects, addProject, and addProjects to User.


Solution

  • This is not an issue related to sequelize at all.

    Look at your error message carefully:

    TypeError: Cannot read property 'addMyusers' of undefined

    It's not that sequelize didn't add the method, it's that your variable items is undefined, and of course undefined does not have a addMyusers method. From the code you posted, items is not set anywhere in your code, so it is indeed undefined.